# Laravel Architecture documentation (v11.x)

> Canonical: https://pharaonic.dev/packages/laravel/architecture/11.x  
> Version: v11.x (latest release 11.0.0, 2026-11-30)  
> Install: composer require pharaonic/laravel-architecture  
> Repository: https://github.com/Pharaonic/laravel-architecture  
> All versions: https://pharaonic.dev/packages/laravel/architecture/13.x.md https://pharaonic.dev/packages/laravel/architecture/12.x.md https://pharaonic.dev/packages/laravel/architecture/11.x.md https://pharaonic.dev/packages/laravel/architecture/10.x.md https://pharaonic.dev/packages/laravel/architecture/9.x.md https://pharaonic.dev/packages/laravel/architecture/8.x.md https://pharaonic.dev/packages/laravel/architecture/7.x.md https://pharaonic.dev/packages/laravel/architecture/6.x.md

:::badges
- Laravel Package {color=blue}
- v11.0.0 {color=green}
- MIT License {color=purple}
- AI Ready {color=violet}
:::

# Laravel Architecture

Architecture gives a Laravel application five small building blocks: Actions for use cases, Tasks for reusable steps, Services for business, integration and module-boundary capabilities, Data objects for typed input and output, and Contexts for state shared during one operation. Each one is a plain abstract class built on what Laravel already ships: the service container, the pipeline, FormRequest validation and Eloquent serialization. Nothing intercepts your calls, wraps your results or enforces rules at runtime.

:::success AI Ready
Architecture ships Laravel Boost resources: a guideline loaded in every session and an architecture-development skill loaded when your agent writes a use case, step, service, DTO or context. Run `php artisan boost:install` and Claude Code, Cursor, Codex, Copilot or Gemini CLI use the package correctly. See [AI Ready](#ai-ready).
:::

:::features
### Actions and Tasks
One class per use case or step, resolved through the container and callable directly or as an invokable.

### Task Pipelines
An Action sends a payload through Tasks with Laravel's own pipeline: closures, classes and parameters included.

### Three Service Categories
Business, Integration and Boundary services share one base class; the category is a convention, not a type.

### Typed Data Objects
Hydrated from arrays, requests and models with strict types, plus MapName, Hidden and DataCollection attributes.

### Generators
make:action, make:task, make:service, make:data and make:context, with nested names and custom paths.

### AI Ready
Laravel Boost guideline and skill, so boost:install teaches your coding agent the whole package.
:::

:::info Quick Tip
Start with one Action per use case and call it from your controller. Add Tasks, Services and a Context only when the use case grows enough to need them.
:::

## Installation

Install the package with Composer; the service provider registers itself. There is no configuration file to publish.

### Requirements

- PHP >= 8.2
- Laravel >= 11.0

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-architecture
```

### Create Your First Action

```bash title="Terminal" no-line-numbers
php artisan make:action CreateOrder
```

The command writes `app/Actions/CreateOrderAction.php`, with the namespace your `composer.json` maps to `app/`.

### Publish the Stubs (optional)

Publish the generator stubs when you want every generated class to start from your own template.

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=architecture-stubs
```

The stubs are copied to `stubs/architecture`. See [Generators](#generators) for the details.

:::success Installation Complete
You're all set! Extend `Pharaonic\Laravel\Architecture\Action`, `Task`, `Service`, `Data` or `Context` in your own classes, or let the generators write them for you.
:::

## Basic Usage

A use case is an Action. It takes typed input, often a Data object, and returns its result.

```php title="app/Data/OrderData.php"
namespace App\Data;

use Pharaonic\Laravel\Architecture\Data;

class OrderData extends Data
{
    public function __construct(
        public int $customerId,
        public string $product,
        public int $quantity = 1,
    ) {}
}
```

```php title="app/Actions/CreateOrderAction.php"
namespace App\Actions;

use App\Data\OrderData;
use App\Models\Order;
use Pharaonic\Laravel\Architecture\Action;

class CreateOrderAction extends Action
{
    public function handle(OrderData $data): Order
    {
        return Order::create([
            'customer_id' => $data->customerId,
            'product' => $data->product,
            'quantity' => $data->quantity,
        ]);
    }
}
```

Call the Action from a controller, a job, a command or a listener. `make()` resolves it through the container, so its constructor dependencies are injected for you.

```php title="app/Http/Controllers/OrderController.php"
public function store(Request $request)
{
    $order = CreateOrderAction::make()->handle(OrderData::fromRequest($request));

    return redirect()->route('orders.show', $order);
}
```

The same Action can be type-hinted, built with `new`, or invoked:

```php
public function store(Request $request, CreateOrderAction $createOrder)
{
    $order = $createOrder(OrderData::fromRequest($request)); // same as ->handle(...)
}
```

### The Five Building Blocks

| Class | Use it for | Exposes |
| --- | --- | --- |
| `Action` | A complete use case, such as creating an order | `make()`, `__invoke()`, `tasks()` |
| `Task` | A small reusable step, such as calculating a total | `make()`, `__invoke()` |
| `Service` | A Business, Integration or Boundary capability | `make()` |
| `Data` | Typed data passed between layers | `fromArray()`, `fromRequest()`, `fromModel()`, `toArray()`, `toJson()`, `with()` |
| `Context` | Mutable state shared during one operation | nothing: it is a marker class |

:::tip Adopt it gradually
Each class works on its own. You can add Actions to an existing application without Tasks, Services or Data, and without moving any code into modules.
:::

## Actions

An Action represents one complete use case with a clear business outcome, such as creating an order or cancelling a subscription. It is the entry point your controllers, jobs, Artisan commands and listeners call.

### Defining an Action

Extend `Action` and add a public `handle()` method. The base class declares no `handle()`, so you choose its parameters and return type freely.

```php title="app/Actions/CancelOrderAction.php"
namespace App\Actions;

use App\Models\Order;
use App\Services\Integration\StripeGatewayService;
use Illuminate\Support\Facades\DB;
use Pharaonic\Laravel\Architecture\Action;

class CancelOrderAction extends Action
{
    public function __construct(protected StripeGatewayService $stripe) {}

    public function handle(Order $order, string $reason = 'customer'): Order
    {
        DB::transaction(function () use ($order, $reason) {
            $order->update(['status' => 'cancelled', 'cancel_reason' => $reason]);
            $order->items()->update(['reserved' => false]);
        });

        $this->stripe->refund($order->charge_id);

        return $order;
    }
}
```

:::info Transactions are yours to manage
Actions add no automatic transaction. Wrap the database writes that must succeed or fail together in `DB::transaction()` yourself. A rollback never undoes external effects such as a refund or an email, so keep those outside the transaction.
:::

### Creating an Action

`make()` resolves the called class through Laravel's service container, like `app()->make(CancelOrderAction::class, $parameters)`. `StripeGatewayService` is defined in [Services](#services).

```php
use GuzzleHttp\Client;

$action = CancelOrderAction::make();

// Override constructor parameters by name; the rest are still resolved.
$action = CancelOrderAction::make(['stripe' => new StripeGatewayService(new Client(['timeout' => 5]))]);
```

Container bindings are respected: if you bind or mock `CancelOrderAction`, `make()` returns that instance. No singleton or scoped lifetime is imposed. Passing parameters always builds a new instance, as Laravel's container does.

You can also build an Action with `new`, or type-hint it anywhere Laravel injects dependencies.

### Calling an Action

`handle()` and the invokable form run the same code and return the same result.

```php
$action->handle($order, 'fraud');
$action($order, 'fraud');
$action($order, reason: 'fraud');   // named arguments are forwarded
```

A `void` handler returns `null` through `__invoke()`. Exceptions propagate unchanged. Calling an Action that has no `handle()` method throws a `BadMethodCallException`.

:::warning References
`__invoke()` forwards its arguments through a variadic parameter, so a `handle()` that takes a parameter by reference (`&$value`) only receives a copy when invoked. Call `handle()` directly when you need the reference.
:::

### Running Tasks Through a Pipeline

An Action can send a payload through a list of Tasks with the protected `tasks()` method, which uses Laravel's `Illuminate\Pipeline\Pipeline`. See [Task Pipelines](#tasks) for the pipe signature; `OrderContext` and the three Tasks are defined in [Contexts](#contexts).

```php title="app/Actions/PlaceOrderAction.php"
namespace App\Actions;

use App\Contexts\OrderContext;
use App\Models\Order;
use App\Tasks\CalculateTotalTask;
use App\Tasks\CreateOrderTask;
use App\Tasks\ReserveStockTask;
use Illuminate\Support\Facades\DB;
use Pharaonic\Laravel\Architecture\Action;

class PlaceOrderAction extends Action
{
    public function handle(OrderContext $context): Order
    {
        return DB::transaction(function () use ($context) {
            return $this->tasks($context, [
                CalculateTotalTask::class,
                ReserveStockTask::class,
                CreateOrderTask::class,
            ])->order;
        });
    }
}
```

### Guidelines

- Keep one use case per Action: creating and cancelling an order are two Actions.
- An Action may call Tasks and Services, query models directly, and call another Action of the same module when it is justified.
- Avoid circular calls between Actions.

## Tasks

A Task is a small, focused operation that several use cases can reuse, such as calculating an order total. It is not a complete use case on its own.

### Defining a Task

A Task works like an Action: extend `Task`, add a public `handle()` method, and inject dependencies through the constructor.

```php title="app/Tasks/CalculateSubtotalTask.php"
namespace App\Tasks;

use App\Services\Business\PricingService;
use Pharaonic\Laravel\Architecture\Task;

class CalculateSubtotalTask extends Task
{
    public function __construct(protected PricingService $pricing) {}

    public function handle(array $items): float
    {
        return array_sum(array_map(fn (array $item) => $this->pricing->price($item), $items));
    }
}
```

```php
$items = [['sku' => 'A-1', 'price' => 50.0, 'quantity' => 2]];

$subtotal = CalculateSubtotalTask::make()->handle($items); // 100.0
$subtotal = CalculateSubtotalTask::make()($items);
```

`PricingService` is defined in [Services](#services). `make()`, `__invoke()`, named arguments, `void` handlers and exceptions behave exactly as they do on an [Action](#actions). Tasks have no `tasks()` method.

### Task Pipelines

A Task used in a pipeline is still a regular Task: give its `handle()` the signature Laravel's pipeline expects, take the payload, and pass it on with `$next`. This one works on the `OrderContext` defined in [Contexts](#contexts).

```php title="app/Tasks/CalculateTotalTask.php"
namespace App\Tasks;

use App\Contexts\OrderContext;
use Closure;
use Pharaonic\Laravel\Architecture\Task;

class CalculateTotalTask extends Task
{
    public function handle(mixed $payload, Closure $next): mixed
    {
        /** @var OrderContext $payload */
        $payload->total = collect($payload->items)->sum(fn ($item) => $item['price'] * $item['quantity']);

        return $next($payload);
    }
}
```

`php artisan make:task CalculateTotal --pipeline` writes this shape for you.

An Action runs the pipeline with `$this->tasks($payload, $tasks)`. The behavior is Laravel's own pipeline:

| Pipe | How it runs |
| --- | --- |
| A class name | Resolved through the container, then `handle($payload, $next)` |
| `Class:first,second` | Same, with `'first'` and `'second'` passed after `$next` |
| An object | `handle($payload, $next)` when it has one, otherwise `__invoke($payload, $next)` |
| A closure | `fn ($payload, Closure $next) => ...` |

- Pipes run in the order you list them, and each receives what the previous one passed to `$next`.
- A pipe may change the payload or replace it entirely; the pipeline returns what the last pipe returns.
- A pipe that returns without calling `$next` stops the pipeline: its return value is the result, even `null`.
- An empty list returns the payload unchanged. Exceptions propagate.
- The payload can be anything: a Context, a Data object, a model, an array, a scalar or `null`.

:::tip Pipes do not have to be Tasks
Any class, object or closure Laravel's pipeline accepts works in `tasks()`. Extending `Task` simply gives the class `make()` and an invokable form for use outside a pipeline.
:::

### Guidelines

- Tasks may call other Tasks of the same module, Services, models and the database.
- Tasks should not call Actions.

## Services

A Service groups a capability behind ordinary public methods. Every service extends the same `Service` class, which only adds `make()`.

```php title="app/Services/Business/PricingService.php"
namespace App\Services\Business;

use Pharaonic\Laravel\Architecture\Service;

class PricingService extends Service
{
    public function price(array $item): float
    {
        return $item['price'] * $item['quantity'];
    }

    public function withTax(float $amount, float $rate): float
    {
        return round($amount * (1 + $rate), 2);
    }
}
```

```php
$pricing = PricingService::make();
$pricing->withTax($pricing->price(['price' => 50.0, 'quantity' => 2]), 0.14); // 114.0
```

An Integration service wraps one external system. This one talks to Stripe's HTTP API with Guzzle, which Laravel 11 applications install by default.

```php title="app/Services/Integration/StripeGatewayService.php"
namespace App\Services\Integration;

use GuzzleHttp\Client;
use Pharaonic\Laravel\Architecture\Service;

class StripeGatewayService extends Service
{
    public function __construct(protected Client $http) {}

    public function charge(string $customerId, int $amountInCents): string
    {
        return $this->send('charges', [
            'customer' => $customerId,
            'amount' => $amountInCents,
            'currency' => 'usd',
        ]);
    }

    public function refund(string $chargeId): string
    {
        return $this->send('refunds', ['charge' => $chargeId]);
    }

    private function send(string $endpoint, array $parameters): string
    {
        $response = $this->http->post('https://api.stripe.com/v1/'.$endpoint, [
            'auth' => [config('services.stripe.secret'), ''],
            'form_params' => $parameters,
        ]);

        return json_decode((string) $response->getBody(), true)['id'];
    }
}
```

A Service has no `handle()` and is not invokable. Define as many public methods as the capability needs, with any signatures. Statelessness is recommended but not required.

### Categories

There are three categories of Service. They are a convention for responsibilities and folders; all of them extend the same class, and nothing checks the category at runtime.

| Category | Responsibility | Default folder |
| --- | --- | --- |
| Business | Cohesive internal business capabilities: reads, writes and business rules, without orchestrating a whole use case | `app/Services/Business` |
| Integration | Talking to external APIs, SDKs and systems: communication, authentication, data transformation, integration errors | `app/Services/Integration` |
| Boundary | The thin public interface of a module, which other modules call instead of its internal classes | `app/Services/Boundary` |

```bash title="Terminal" no-line-numbers
php artisan make:service Pricing # Business (the default)
php artisan make:service Stripe --integration
php artisan make:service Orders --boundary
```

### Guidelines

- **Business** services may use Integration and Boundary services and the database. They should not call Actions, Tasks or other Business services.
- **Integration** services should stay independent of Actions, Tasks and other Services. They may store integration state, such as access tokens, in the database.
- **Boundary** services may delegate to the Actions, Tasks and Business services their own module owns, or do simple local work. Avoid calling other Boundary or Integration services from them.

## Dependency Guidelines

These recommendations describe which component should call which directly. They are documentation only: the package does not validate or enforce them, and they are not a required call sequence.

| Caller | Action | Task | Business | Integration | Boundary | Model / DB |
| --- | --- | --- | --- | --- | --- | --- |
| Action | Same module | Same module | Allowed | Allowed | Allowed | Allowed |
| Task | Discouraged | Same module | Allowed | Allowed | Allowed | Allowed |
| Business | Discouraged | Discouraged | Discouraged | Allowed | Allowed | Allowed |
| Integration | Discouraged | Discouraged | Discouraged | Discouraged | Discouraged | Integration needs only |
| Boundary | Own module | Own module | Own module | Discouraged | Discouraged | Own module |

- "Same module" applies to internal Actions, Tasks, Business services and models.
- Integration dependencies should respect module ownership or explicitly public contracts.
- A Boundary dependency means the other module's public Boundary service.
- Avoid circular dependencies, including indirect cycles across modules.
- Pass Data and Context objects explicitly where they help.

### Validation and Authorization

Validate input where it arrives, usually in a FormRequest, before it reaches an Action. Business validation and authorization may live in Actions, Tasks or Services. Use Laravel's validation, authorization and exceptions: the package adds no validation API, result wrapper or required return type.

:::info Modules are optional
"Module" here means any folder of related code you choose. The package does not require a modules package; generators accept a `--path` for any PSR-4 folder.
:::

## Data Objects

A Data object carries structured, typed data between layers. Declare its fields as constructor-promoted public properties; immutable objects are recommended but not required.

```php title="app/Data/UserData.php"
namespace App\Data;

use Pharaonic\Laravel\Architecture\Data;

class UserData extends Data
{
    public function __construct(
        public string $name,
        public string $email,
        public bool $active = true,
    ) {}
}
```

Keep business logic and execution state out of Data objects: they describe values, and a [Context](#contexts) holds state.

### From an Array

`fromArray()` builds the object through its constructor, matching array keys to constructor parameter names. Key order does not matter.

```php
$user = UserData::fromArray([
    'email' => 'user@example.com',
    'name' => 'Ahmed',
    'role' => 'admin',          // ignored: not a constructor parameter
]);

$user->active; // true (the constructor default)
```

| Input | Result |
| --- | --- |
| Extra keys | Ignored |
| A missing parameter that has a default | The default is used |
| A missing parameter without a default | `InvalidArgumentException`, even when its type is nullable |
| `null` | Accepted only when the type allows `null` |
| A value of the wrong type | `TypeError`: values are never coerced, so `'2'` is not an `int` (an `int` still widens to `float`, as in PHP) |

The constructor always runs, and no dynamic properties are created. There is no validation engine: validate input before building the object, for example with a FormRequest.

### From a Request

`fromRequest()` uses `validated()` when the request is a FormRequest, and `all()` for any other request.

- ===Request

  ```php title="app/Http/Requests/StoreUserRequest.php"
  namespace App\Http\Requests;

  use Illuminate\Foundation\Http\FormRequest;

  class StoreUserRequest extends FormRequest
  {
      public function rules()
      {
          return [
              'name' => 'required|string|max:255',
              'email' => 'required|email',
          ];
      }
  }
  ```

- ===Controller

  ```php title="app/Http/Controllers/UserController.php"
  namespace App\Http\Controllers;

  use App\Data\UserData;
  use App\Http\Requests\StoreUserRequest;

  class UserController extends Controller
  {
      public function store(StoreUserRequest $request)
      {
          $user = UserData::fromRequest($request); // only name and email

          // ...
      }
  }
  ```

:::warning Plain requests are not validated
For an ordinary `Illuminate\Http\Request`, `fromRequest()` uses every input field as is. To build from input you validated yourself, pass it to `fromArray()`: `UserData::fromArray($request->validate([...]))`.
:::

### From a Model

`fromModel()` is `fromArray($model->toArray())`, so Eloquent decides what is included: casts, accessors in `$appends`, `$hidden` and `$visible`, and relations that are already loaded.

```php title="app/Data/ProfileData.php"
namespace App\Data;

use Pharaonic\Laravel\Architecture\Data;

class ProfileData extends Data
{
    public function __construct(
        public string $name,
        public string $email,
        public ?AddressData $address = null,   // filled when the relation is loaded
    ) {}
}
```

```php
$profile = ProfileData::fromModel($user->load('address'));
```

It never loads relations on its own and never reveals hidden attributes. Accessors run as part of Eloquent's serialization.

### Nested Data

A parameter typed with a concrete Data class is built from an array automatically; an instance of that class is accepted as is.

```php title="app/Data/AddressData.php"
namespace App\Data;

use Pharaonic\Laravel\Architecture\Data;

class AddressData extends Data
{
    public function __construct(
        public string $city,
        public ?string $street = null,
    ) {}
}
```

```php title="app/Data/PersonData.php"
class PersonData extends Data
{
    public function __construct(
        public string $name,
        public AddressData $address,
        public ?AddressData $billing = null,
    ) {}
}

$person = PersonData::fromArray([
    'name' => 'Ahmed',
    'address' => ['city' => 'Alexandria'],
]);

$person->address->city; // "Alexandria"
```

Union types such as `AddressData|array` are never guessed: the value is passed to the constructor unchanged. For lists of Data, use the [DataCollection](#data-attributes) attribute.

### Serialization

`toArray()` returns the object's initialized public properties, with nested Data, arrays and collections converted recursively. `jsonSerialize()` returns the same array, and `toJson()` encodes it.

```php
$user->toArray();                            // ['name' => 'Ahmed', 'email' => 'user@example.com', 'active' => true]
$user->toJson(JSON_PRETTY_PRINT);            // your JSON options are respected
return response()->json($user);             // Data is JsonSerializable
```

- Static, protected and private properties are never included, and no getter is called.
- A typed public property that was never initialized is left out instead of failing.
- Values implementing `Arrayable`, such as models and collections, are converted with their own `toArray()`, as Laravel's collections do. Other objects are left for `json_encode`.
- `toJson()` throws a `JsonException` when the data cannot be encoded, for example invalid UTF-8; it never returns `false`.
- A Data object that contains itself throws a `LogicException` instead of recursing forever.

### Updating a Copy

`with()` returns a new instance of the same class with some fields replaced, and leaves the original unchanged.

```php
$updated = $user->with(['name' => 'Mohamed']);

$user->name;    // "Ahmed"
$updated->name; // "Mohamed"
```

- Use PHP property names, not `MapName` names. An unknown key throws `InvalidArgumentException`.
- Every other field is copied from the current object, including hidden and protected promoted properties.
- New values follow the same rules as `fromArray()`: types, nested Data and collections.
- The new object is built through the constructor, so readonly properties (PHP 8.1+) work.
- Nested objects are copied by reference; `with()` is not a deep clone.

:::info Constructors with non-promoted parameters
`with()` copies each constructor parameter from the property of the same name. When a parameter has no such property, `with()` throws a `LogicException`. Variadic constructor parameters are not supported by any hydration method.
:::

## Data Attributes

Three attributes, in `Pharaonic\Laravel\Architecture\Attributes`, adjust how a Data object is hydrated and serialized. Put them on promoted constructor parameters, or on a property and its constructor parameter.

### MapName

`MapName` gives a field a different external name, used both to read input and to write output.

```php title="app/Data/CustomerData.php"
use Pharaonic\Laravel\Architecture\Attributes\MapName;
use Pharaonic\Laravel\Architecture\Data;

class CustomerData extends Data
{
    public function __construct(
        #[MapName('first_name')]
        public string $firstName,
    ) {}
}

$customer = CustomerData::fromArray(['first_name' => 'Ahmed']);

$customer->firstName; // "Ahmed"
$customer->toArray(); // ['first_name' => 'Ahmed']
```

- There is no automatic case conversion: fields without `MapName` keep their PHP name.
- Input is read by the external name only; `['firstName' => ...]` does not match.
- `with()` uses PHP names: `$customer->with(['firstName' => 'Mohamed'])`.
- Two fields mapped to the same name, or different names declared on a property and its parameter, throw a `LogicException`.

### Hidden

`Hidden` leaves a field out of `toArray()`, `toJson()` and `jsonSerialize()`, including when the object is nested inside another one.

```php
use Pharaonic\Laravel\Architecture\Attributes\Hidden;

class AccountData extends Data
{
    public function __construct(
        public string $email,
        #[Hidden]
        public string $apiToken,
    ) {}
}

$account->apiToken;  // still readable
$account->toArray(); // ['email' => '...']
```

`Hidden` does not affect hydration, property access or `with()`.

:::warning Not a security boundary
`Hidden` only changes serialization. It does not encrypt the value or stop code, `var_dump()` or logs from reading it.
:::

### DataCollection

`DataCollection` names the Data class of each element of an `array` or `Illuminate\Support\Collection` field.

```php title="app/Data/OrderItemData.php"
namespace App\Data;

use Pharaonic\Laravel\Architecture\Data;

class OrderItemData extends Data
{
    public function __construct(
        public string $sku,
        public int $quantity = 1,
    ) {}
}
```

```php title="app/Data/OrderData.php"
use Illuminate\Support\Collection;
use Pharaonic\Laravel\Architecture\Attributes\DataCollection;
use Pharaonic\Laravel\Architecture\Data;

class OrderData extends Data
{
    public function __construct(
        #[DataCollection(OrderItemData::class)]
        public array $items,
        #[DataCollection(OrderItemData::class)]
        public ?Collection $gifts = null,
    ) {}
}

$order = OrderData::fromArray([
    'items' => [
        ['sku' => 'A-1', 'quantity' => 2],
        ['sku' => 'B-7'],
    ],
]);

$order->items[0]; // OrderItemData
```

- Each element is built from an array with `fromArray()`, or kept when it is already an instance of the class.
- The field gets the type it declares: an `array`, or a new `Collection`. Either one is accepted as input.
- Keys are preserved, and an empty list is valid. A nullable field accepts `null`.
- Any other element, such as a string or another Data class, throws a `TypeError` that names the field and key.
- `toArray()` converts every element back to an array, keeping the keys.

A `DataCollection` that names a class that is not a concrete Data class, or that sits on a field whose type is not `array` or `Collection`, throws a `LogicException` the first time the class is used. There is no inference from PHPDoc: declare the attribute whenever a list holds Data objects.

## Contexts

A Context holds mutable state for one operation and is passed explicitly between the components that share it, typically the Tasks of a pipeline.

```php title="app/Contexts/OrderContext.php"
namespace App\Contexts;

use App\Models\Order;
use App\Models\User;
use Pharaonic\Laravel\Architecture\Context;

class OrderContext extends Context
{
    public float $total = 0;
    public ?string $coupon = null;
    public ?Order $order = null;

    /**
     * @param  array<int, array{sku: string, price: float, quantity: int}>  $items
     */
    public function __construct(public User $user, public array $items = []) {}
}
```

### Sharing It Through a Pipeline

Each pipeline Task reads what the previous ones wrote and adds its own part.

- ===CalculateTotalTask

  ```php title="app/Tasks/CalculateTotalTask.php"
  namespace App\Tasks;

  use App\Contexts\OrderContext;
  use Closure;
  use Pharaonic\Laravel\Architecture\Task;

  class CalculateTotalTask extends Task
  {
      public function handle(mixed $payload, Closure $next): mixed
      {
          /** @var OrderContext $payload */
          $payload->total = collect($payload->items)->sum(fn ($item) => $item['price'] * $item['quantity']);

          return $next($payload);
      }
  }
  ```

- ===ReserveStockTask

  ```php title="app/Tasks/ReserveStockTask.php"
  namespace App\Tasks;

  use App\Contexts\OrderContext;
  use App\Models\Product;
  use Closure;
  use Pharaonic\Laravel\Architecture\Task;
  use RuntimeException;

  class ReserveStockTask extends Task
  {
      public function handle(mixed $payload, Closure $next): mixed
      {
          /** @var OrderContext $payload */
          foreach ($payload->items as $item) {
              $reserved = Product::where('sku', $item['sku'])
                  ->where('stock', '>=', $item['quantity'])
                  ->decrement('stock', $item['quantity']);

              if ($reserved === 0) {
                  throw new RuntimeException("{$item['sku']} is out of stock.");
              }
          }

          return $next($payload);
      }
  }
  ```

- ===CreateOrderTask

  ```php title="app/Tasks/CreateOrderTask.php"
  namespace App\Tasks;

  use App\Contexts\OrderContext;
  use App\Models\Order;
  use Closure;
  use Pharaonic\Laravel\Architecture\Task;

  class CreateOrderTask extends Task
  {
      public function handle(mixed $payload, Closure $next): mixed
      {
          /** @var OrderContext $payload */
          $payload->order = Order::create([
              'user_id' => $payload->user->id,
              'total' => $payload->total,
              'coupon' => $payload->coupon,
          ]);

          $payload->order->items()->createMany($payload->items);

          return $next($payload);
      }
  }
  ```

The [PlaceOrderAction](#actions) runs them in order inside a transaction:

```php
$context = new OrderContext($request->user(), $request->input('items'));

$order = PlaceOrderAction::make()->handle($context);

$context->total; // set by CalculateTotalTask
$context->order; // set by CreateOrderTask, the same Order returned
```

### What a Context Is Not

`Context` is an empty abstract class. It is not a Data object, and it intentionally offers nothing more:

- no `make()`: create it with `new` and your own constructor;
- no hydration, serialization, magic accessors or key-value storage: declare typed properties;
- no container binding and no automatic propagation: pass it where it is needed.

:::tip One context per operation
Create a new Context for every independent operation. Sharing one instance across requests or queued jobs turns it into global state.
:::

## Generators

Five Artisan commands write a new class from a stub.

| Command | Default folder | Suffix | Class |
| --- | --- | --- | --- |
| `make:action` | `app/Actions` | `Action` | extends `Action`, with an empty `handle(): void` |
| `make:task` | `app/Tasks` | `Task` | extends `Task`, with an empty `handle(): void` |
| `make:task --pipeline` | `app/Tasks` | `Task` | extends `Task`, with `handle(mixed $payload, Closure $next): mixed` |
| `make:service` | `app/Services/Business` | `Service` | extends `Service`, empty body |
| `make:data` | `app/Data` | `Data` | extends `Data`, with an empty constructor |
| `make:context` | `app/Contexts` | `Context` | extends `Context`, empty body |

### Names

```bash title="Terminal" no-line-numbers
php artisan make:action CreateOrder              # app/Actions/CreateOrderAction.php
php artisan make:action CreateOrderAction        # the same file: the suffix is not doubled
php artisan make:action Orders/CreateOrder       # app/Actions/Orders/CreateOrderAction.php
php artisan make:task CalculateTotal --pipeline
```

The suffix is added only when the name does not already end with it (case-sensitive). Every segment must be a valid PHP class name. A name that is only the suffix, such as `Action`, is refused because the class would clash with its base class.

### Service Categories

```bash title="Terminal" no-line-numbers
php artisan make:service Pricing                 # app/Services/Business
php artisan make:service Pricing --business      # app/Services/Business
php artisan make:service Stripe --integration    # app/Services/Integration
php artisan make:service Orders --boundary       # app/Services/Boundary
```

`--business`, `--integration` and `--boundary` are mutually exclusive.

### Custom Paths

`--path` writes into another folder, relative to the project root or absolute. It overrides the default folder, including a service category's.

```bash title="Terminal" no-line-numbers
php artisan make:action CreateOrder --path=modules/Orders/Actions
php artisan make:service Orders --boundary --path=modules/Orders/Services
```

The namespace always comes from the `autoload.psr-4` section of your `composer.json`: the longest mapped folder that contains the destination, plus the remaining folders. Nothing assumes `App`, so an application mapped as `"Acme\\": "app/"` gets `Acme\Actions`.

```json title="composer.json"
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Modules\\": "modules/"
    }
}
```

With this mapping, `--path=modules/Orders/Actions` gives `Modules\Orders\Actions\CreateOrderAction`. The command refuses, and writes nothing, when no mapping contains the folder, when two prefixes map the same folder, or when a folder name is not a valid namespace segment such as `my-orders`. Run `composer dump-autoload` after adding a mapping.

### Overwriting

An existing file is never replaced unless you pass `--force`.

```bash title="Terminal" no-line-numbers
php artisan make:data Order --force
```

### Customizing the Stubs

Publish the stubs to change what every generated class looks like:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=architecture-stubs
```

The files are copied to `stubs/architecture`: `action.stub`, `task.stub`, `task.pipeline.stub`, `service.stub`, `data.stub` and `context.stub`. Each one uses the `{{ namespace }}` and `{{ class }}` tokens. A stub you delete falls back to the package's version. The `pharaonic`, `laravel-architecture` and `pharaonic-stubs` tags publish the same files.

:::info Command names
Laravel itself has no `make:action`, `make:task`, `make:service`, `make:data` or `make:context`. If another package registers one of these names after this package, Artisan uses the one registered last.
:::

Every command exits with `0` when the file is written and `1` when it refuses.

## AI Ready

Architecture is AI ready. It ships [Laravel Boost](https://laravel.com/docs/boost) resources, so the coding agent in your application (Claude Code, Cursor, Codex, Copilot, Gemini CLI, Junie…) knows how to write Actions, Tasks, Services, Data objects and Contexts with it.

### Install

With Laravel Boost in your application, run:

```bash title="Terminal" no-line-numbers
php artisan boost:install
```

Boost finds the package's guideline and skill in `vendor/` and adds them for the agents you choose. After updating the package, refresh them with:

```bash title="Terminal" no-line-numbers
php artisan boost:update
```

### What the Agent Learns

| Resource | Loaded | Covers |
| --- | --- | --- |
| Guideline (`resources/boost/guidelines/core.blade.php`) | In every session | The five classes, `make()` and `handle()`, task pipelines, Data objects and their attributes, the generators, and what the package never does for you |
| Skill `architecture-development` | When the agent writes or changes a use case, step, service, DTO or context | Choosing a component, the dependency guidelines, every public method, hydration rules, attributes, generator options, pitfalls and testing |

:::tip Keep Them Current
Add `@php artisan boost:update --ansi` to your Composer `post-update-cmd` scripts so the agent always matches the installed release.
:::

## API Reference

All classes are in the `Pharaonic\Laravel\Architecture` namespace.

### Action

| Method | Description | Returns |
| --- | --- | --- |
| `static make(array $parameters = [])` | Resolves the class through the container; `$parameters` overrides constructor parameters by name | `static` |
| `__invoke(mixed ...$arguments)` | Calls your `handle()` with the same positional and named arguments | `mixed` (`null` for a `void` handler) |
| `protected tasks(mixed $payload, array $tasks)` | Sends `$payload` through Laravel's pipeline | `mixed`, what the pipeline returns |

### Task

| Method | Description | Returns |
| --- | --- | --- |
| `static make(array $parameters = [])` | Resolves the class through the container | `static` |
| `__invoke(mixed ...$arguments)` | Calls your `handle()` | `mixed` |

### Service

| Method | Description | Returns |
| --- | --- | --- |
| `static make(array $parameters = [])` | Resolves the class through the container | `static` |

### Data

Implements `Illuminate\Contracts\Support\Arrayable`, `Illuminate\Contracts\Support\Jsonable` and `JsonSerializable`.

| Method | Description | Returns |
| --- | --- | --- |
| `static fromArray(array $data)` | Builds the object through its constructor from an associative array | `static` |
| `static fromRequest(Request $request)` | `validated()` of a FormRequest, `all()` of any other request, then `fromArray()` | `static` |
| `static fromModel(Model $model)` | `fromArray($model->toArray())` | `static` |
| `toArray()` | Initialized public properties by external name, without hidden ones, converted recursively | `array` |
| `toJson($options = 0)` | JSON of `toArray()` with your `json_encode` options | `string` |
| `jsonSerialize()` | Same as `toArray()` | `array` |
| `with(array $attributes)` | A new instance with the given fields, by PHP name, replaced | `static` |

### Attributes

| Attribute | Target | Effect |
| --- | --- | --- |
| `Attributes\MapName(string $name)` | Property or constructor parameter | External name for hydration and serialization |
| `Attributes\Hidden` | Property or constructor parameter | Left out of `toArray()`, `toJson()` and `jsonSerialize()` |
| `Attributes\DataCollection(string $class)` | `array` or `Collection` property or parameter | Builds each element as `$class` |

### Context

An empty abstract class with no methods.

### Exceptions

The package uses PHP's own exceptions; it defines none.

| Exception | Thrown when |
| --- | --- |
| `BadMethodCallException` | An Action or Task is invoked without a `handle()` method |
| `InvalidArgumentException` | `fromArray()` misses a required field; `with()` gets a key that is not a constructor parameter |
| `TypeError` | A value does not match its declared type, or a `DataCollection` element is not an array or an instance of its class |
| `LogicException` | A Data class declares duplicate or conflicting `MapName`s, an empty `MapName`, an invalid `DataCollection`, or a variadic constructor; `with()` cannot copy a parameter; a Data object contains itself |
| `JsonException` | `toJson()` cannot encode the data |

### Commands

| Command | Arguments and options |
| --- | --- |
| `make:action` | `{name}` `--path=` `--force` |
| `make:task` | `{name}` `--path=` `--force` `--pipeline` |
| `make:service` | `{name}` `--path=` `--force` `--business` `--integration` `--boundary` |
| `make:data` | `{name}` `--path=` `--force` |
| `make:context` | `{name}` `--path=` `--force` |

### Publish Tags

| Tag | Publishes |
| --- | --- |
| `architecture-stubs` | The generator stubs to `stubs/architecture` |
| `pharaonic-stubs`, `laravel-architecture`, `pharaonic` | The same files |

## Examples

### 1. Controller, FormRequest, Data and Action

The request validates the input, the Data objects type it, and the Action does the work.

- ===Request

  ```php title="app/Http/Requests/StoreOrderRequest.php"
  namespace App\Http\Requests;

  use Illuminate\Foundation\Http\FormRequest;

  class StoreOrderRequest extends FormRequest
  {
      public function rules()
      {
          return [
              'items' => 'required|array|min:1',
              'items.*.sku' => 'required|string',
              'items.*.quantity' => 'required|integer|min:1',
              'coupon' => 'nullable|string',
          ];
      }
  }
  ```

- ===Item Data

  ```php title="app/Data/OrderItemData.php"
  namespace App\Data;

  use Pharaonic\Laravel\Architecture\Data;

  class OrderItemData extends Data
  {
      public function __construct(
          public string $sku,
          public int $quantity = 1,
      ) {}
  }
  ```

- ===Order Data

  ```php title="app/Data/OrderData.php"
  namespace App\Data;

  use Pharaonic\Laravel\Architecture\Attributes\DataCollection;
  use Pharaonic\Laravel\Architecture\Data;

  class OrderData extends Data
  {
      public function __construct(
          #[DataCollection(OrderItemData::class)]
          public array $items,
          public ?string $coupon = null,
      ) {}
  }
  ```

- ===Action

  ```php title="app/Actions/CreateOrderAction.php"
  namespace App\Actions;

  use App\Data\OrderData;
  use App\Models\Order;
  use Illuminate\Support\Facades\DB;
  use Pharaonic\Laravel\Architecture\Action;

  class CreateOrderAction extends Action
  {
      public function handle(OrderData $data, int $userId): Order
      {
          return DB::transaction(function () use ($data, $userId) {
              $order = Order::create(['user_id' => $userId, 'coupon' => $data->coupon]);

              foreach ($data->items as $item) {
                  $order->items()->create($item->toArray());
              }

              return $order;
          });
      }
  }
  ```

- ===Controller

  ```php title="app/Http/Controllers/OrderController.php"
  namespace App\Http\Controllers;

  use App\Actions\CreateOrderAction;
  use App\Data\OrderData;
  use App\Http\Requests\StoreOrderRequest;

  class OrderController extends Controller
  {
      public function store(StoreOrderRequest $request, CreateOrderAction $createOrder)
      {
          $order = $createOrder(OrderData::fromRequest($request), $request->user()->id);

          return redirect()->route('orders.show', $order);
      }
  }
  ```

### 2. A Checkout Pipeline With a Coupon Step

Add a step to the order pipeline from [Contexts](#contexts) without touching the other Tasks.

- ===ApplyCouponTask

  ```php title="app/Tasks/ApplyCouponTask.php"
  namespace App\Tasks;

  use App\Contexts\OrderContext;
  use Closure;
  use Pharaonic\Laravel\Architecture\Task;

  class ApplyCouponTask extends Task
  {
      public function handle(mixed $payload, Closure $next, string $code = 'WELCOME10', string $percent = '10'): mixed
      {
          /** @var OrderContext $payload */
          if ($payload->coupon === $code) {
              $payload->total = round($payload->total * (1 - (int) $percent / 100), 2);
          }

          return $next($payload);
      }
  }
  ```

- ===CheckoutAction

  ```php title="app/Actions/CheckoutAction.php"
  namespace App\Actions;

  use App\Contexts\OrderContext;
  use App\Models\Order;
  use App\Tasks\ApplyCouponTask;
  use App\Tasks\CalculateTotalTask;
  use App\Tasks\CreateOrderTask;
  use App\Tasks\ReserveStockTask;
  use Illuminate\Support\Facades\DB;
  use Pharaonic\Laravel\Architecture\Action;

  class CheckoutAction extends Action
  {
      public function handle(OrderContext $context): Order
      {
          return DB::transaction(function () use ($context) {
              return $this->tasks($context, [
                  CalculateTotalTask::class,
                  ApplyCouponTask::class.':SUMMER20,20',
                  ReserveStockTask::class,
                  CreateOrderTask::class,
              ])->order;
          });
      }
  }
  ```

- ===Controller

  ```php title="app/Http/Controllers/CheckoutController.php"
  namespace App\Http\Controllers;

  use App\Actions\CheckoutAction;
  use App\Contexts\OrderContext;
  use Illuminate\Http\Request;

  class CheckoutController extends Controller
  {
      public function store(Request $request, CheckoutAction $checkout)
      {
          $context = new OrderContext($request->user(), $request->validate([
              'items' => 'required|array|min:1',
              'items.*.sku' => 'required|string',
              'items.*.price' => 'required|numeric',
              'items.*.quantity' => 'required|integer|min:1',
          ])['items']);
          $context->coupon = $request->input('coupon');

          return redirect()->route('orders.show', $checkout($context));
      }
  }
  ```

The `:SUMMER20,20` suffix passes `'SUMMER20'` and `'20'` to the Task after `$next`, as Laravel's pipeline does for middleware parameters.

### 3. An Action From a Queued Job

Jobs stay thin: they hold the input and call the Action.

- ===SendInvoiceAction

  ```php title="app/Actions/SendInvoiceAction.php"
  namespace App\Actions;

  use App\Models\Order;
  use Illuminate\Support\Facades\Mail;
  use Pharaonic\Laravel\Architecture\Action;

  class SendInvoiceAction extends Action
  {
      public function handle(Order $order): void
      {
          Mail::raw("Your order #{$order->id} totals {$order->total}.", function ($message) use ($order) {
              $message->to($order->user->email)->subject("Invoice #{$order->id}");
          });

          $order->update(['invoiced_at' => now()]);
      }
  }
  ```

- ===Job

  ```php title="app/Jobs/SendInvoice.php"
  namespace App\Jobs;

  use App\Actions\SendInvoiceAction;
  use App\Models\Order;
  use Illuminate\Bus\Queueable;
  use Illuminate\Contracts\Queue\ShouldQueue;
  use Illuminate\Queue\SerializesModels;

  class SendInvoice implements ShouldQueue
  {
      use Queueable, SerializesModels;

      public function __construct(public Order $order) {}

      public function handle(SendInvoiceAction $sendInvoice)
      {
          $sendInvoice($this->order);
      }
  }
  ```

The same Action works from a console command or a listener; nothing in it depends on where it is called from.

### 4. A Boundary Service in Front of a Module

Other modules reach billing through `BillingService` only. Behind it, an Action uses the `StripeGatewayService` integration from [Services](#services).

- ===Boundary Service

  ```php title="modules/Billing/Services/BillingService.php"
  namespace Modules\Billing\Services;

  use Modules\Billing\Actions\ChargeCustomerAction;
  use Pharaonic\Laravel\Architecture\Service;

  class BillingService extends Service
  {
      public function __construct(protected ChargeCustomerAction $charge) {}

      public function charge(int $userId, int $amountInCents): string
      {
          return $this->charge->handle($userId, $amountInCents);
      }
  }
  ```

- ===Action

  ```php title="modules/Billing/Actions/ChargeCustomerAction.php"
  namespace Modules\Billing\Actions;

  use App\Services\Integration\StripeGatewayService;
  use App\Models\User;
  use Pharaonic\Laravel\Architecture\Action;

  class ChargeCustomerAction extends Action
  {
      public function __construct(protected StripeGatewayService $stripe) {}

      public function handle(int $userId, int $amountInCents): string
      {
          $user = User::findOrFail($userId);

          return $this->stripe->charge($user->stripe_id, $amountInCents);
      }
  }
  ```

```bash title="Terminal" no-line-numbers
php artisan make:service Billing --boundary --path=modules/Billing/Services
php artisan make:action ChargeCustomer --path=modules/Billing/Actions
```

Both commands need `"Modules\\": "modules/"` in the `autoload.psr-4` section of `composer.json`.

### 5. Testing With Laravel's Mocks

`make()` and constructor injection both resolve through the container, so Laravel's usual mocking works without a package-specific API. This test charges a customer through the boundary from example 4 without calling Stripe.

```php title="tests/Feature/BillingTest.php"
namespace Tests\Feature;

use App\Services\Integration\StripeGatewayService;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Modules\Billing\Services\BillingService;
use Tests\TestCase;

class BillingTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_charges_the_customer_through_stripe()
    {
        $user = User::factory()->create(['stripe_id' => 'cus_123']);

        $this->mock(StripeGatewayService::class, function ($mock) {
            $mock->shouldReceive('charge')->once()->with('cus_123', 5000)->andReturn('ch_123');
        });

        $this->assertSame('ch_123', BillingService::make()->charge($user->id, 5000));
    }
}
```

## Troubleshooting

### "The field [x] is required to create [...]"

`fromArray()` did not find a key for a constructor parameter that has no default. A nullable type does not make a field optional. Give the parameter a default (`public ?string $nickname = null`) or include the key. When the field uses `MapName`, the message shows the external name first: send that key.

### TypeError when building a Data object

Values are not coerced. A form field `"2"` does not fit an `int` parameter. Cast the value before building the object, or validate and convert it in your FormRequest.

### A mapped field stays empty

Input is matched by the `MapName` name only. `['firstName' => ...]` does not fill a field mapped to `first_name`. In `with()`, it is the other way around: use the PHP name.

### "[...] has no constructor parameter [...]" from with()

`with()` takes PHP property names and rejects unknown keys. Check for a typo or a `MapName` name.

### "[...] maps the fields [a] and [b] to the same name [b]"

Two fields would read and write the same key. Change one of the `MapName` values.

### "No autoload.psr-4 path of composer.json contains [...]"

The generator cannot tell the namespace of the destination folder. Add a PSR-4 mapping for it in `composer.json`, run `composer dump-autoload`, and run the command again.

### "[...] already exists. Use --force to overwrite it."

Generators never replace a file silently. Pass `--force` to overwrite it.

### My published stub is ignored

Published stubs must be in `stubs/architecture` at the project root, with the original file name, such as `action.stub`. A stub that is missing from that folder falls back to the package's.

### A pipeline stops early

A pipe that returns without calling `$next($payload)` ends the pipeline, and its return value becomes the result. Make sure every pipeline Task returns `$next($payload)`.

### make:action runs another package's command

Another package registered the same command name after this one. Artisan keeps the last registration. Check `php artisan list make` and the order of your service providers.
