laravel-dtos
Installation
SKILL.md
Laravel DTOs
Structured data that crosses a layer boundary, such as an operation's input, travels as a DTO: a spatie/laravel-data class extending the app's own base Data. Filling one is explicit. Every input key is read with a typed request helper and handed to a named property, so the mapping reads top to bottom and nothing depends on laravel-data guessing names or casting raw strings. The Form Request validates; the DTO only carries.
Rules
- Extend
App\Data\Data, never Spatie's class. The base addstestFactory()andhas('prop'), which is false for null,Optionalor an empty Collection. Copy Data.php. - Name for what it carries.
{Verb}{Entity}Datafor an operation's input (CreateOrderData),{Entity}Datafor an entity's shape,{Descriptor}{Entity}Datafor a part (ShippingAddressData). They live inapp/Data/; a DTO only one service uses lives inapp/Services/{Name}/Data/. - Promoted, typed constructor properties. A list is a
Collectionwith/** @var Collection<int, OrderItemData> */above the parameter: laravel-data reads that to build the children. Dates areCarbonImmutable. - Map with typed request helpers.
$request->date(),->enum(),->boolean(),->integer(),->collect(),->input('tags', []). Values arrive already typed, so laravel-data never has to cast a raw request string. - Map names by hand. snake_case input goes to camelCase properties key by key. No
#[MapInputName]or mapper attributes on a DTO filled from a request: the transformer is the one place a reader sees which key lands where. - Validation is the Form Request's; laravel-data's is off. Set
validation_strategytodisabled(see Configuration). Left at the default,CreateOrderData::from($request)runs laravel-data's pipeline over the raw request before calling your creation method: rules inferred from camelCase properties meet snake_case input, and a request the Form Request passed fails with a 422. - Usually, a transformer per surface.
App\Data\Transformers\{Surface}\{Dto}Transformer, the surface mirroringApp\Http\{Surface}(Api\V1,Web), with onefromRequest()that type-hints the surface's Form Request. Each surface's mapping stays separate and explicit: a V2 API maps into the same DTO without touching V1. A transformer that returns a list is{Item}DataCollectionTransformer, returningCollection<int, ItemData>. This is the usual choice, not an absolute one; the alternative follows. - A model is mapped explicitly too. Write a
fromModel()(or a transformer), never a bareOrderData::from($order). The model normaliser matches attributes by name, so snake_case columns miss camelCase properties and nullable ones arrive as null without complaint. - Transformers only map. No writes, events or business rules. Those belong in the action that takes the DTO.
- Test data comes from
testFactory(), neverfactory(), which laravel-data already uses for its creation-context builder.