AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
SKILL verified MIT Self-run

Laravel Dtos

skill-leeovery-agentic-skills-laravel-dtos · by leeovery

Data Transfer Objects using Spatie Laravel Data. Use when creating or modifying DTOs, data objects, formatters, transformers, or structured data handling.

No reviews yet
0 installs
6 views
0.0% view→install

Install

$ agentstack add skill-leeovery-agentic-skills-laravel-dtos

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/skill-leeovery-agentic-skills-laravel-dtos)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
1mo ago

Declared compatibility

Claude CodeClaude Desktop

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Laravel Dtos? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Laravel DTOs

Never pass multiple primitive values. Always wrap data in Data objects.

Related guides:

  • [dto-transformers.md](references/dto-transformers.md) - Transform external data into DTOs
  • [test-factories.md](references/test-factories.md) - Create hydrated DTOs for tests

Philosophy

DTOs provide:

  • Type safety and IDE autocomplete
  • Clear contracts between layers
  • Test factories for easy test data generation
  • Validation integration
  • Transformation from requests to domain objects

Spatie Laravel Data Package

Uses Spatie Laravel Data. Refer to official docs for package features. This guide covers project-specific patterns and preferences.

Use ::from() with Arrays

Always prefer ::from() with arrays where keys match constructor property names. Let the package handle casting based on property types.

// ✅ PREFERRED - Let package cast automatically
$data = CreateOrderData::from([
    'customerEmail' => $request->input('customer_email'),
    'deliveryDate' => $request->input('delivery_date'),  // String → CarbonImmutable
    'status' => $request->input('status'),               // String → OrderStatus enum
    'items' => $request->collect('items'),               // Array → Collection
]);

// ❌ AVOID - Manual casting in calling code
$data = new CreateOrderData(
    customerEmail: $request->input('customer_email'),
    deliveryDate: CarbonImmutable::parse($request->input('delivery_date')),
    status: OrderStatus::from($request->input('status')),
    items: OrderItemData::collect($request->input('items')),
);

Why prefer ::from():

  • Package handles type casting automatically based on constructor property types
  • Cleaner calling code without manual casting
  • Consistent transformation behavior
  • Leverages the full power of the package

When new is acceptable:

  • In test factories where you control all values
  • When values are already the correct type
  • In formatters inside the DTO constructor

Avoid Case Mapper Attributes

Don't use #[MapInputName] or case mapper attributes. Map field names explicitly in calling code.

// ❌ AVOID - Case mapper attributes on the class
#[MapInputName(SnakeCaseMapper::class)]
class CreateOrderData extends Data
{
    public function __construct(
        public string $customerEmail,    // Auto-maps from 'customer_email'
    ) {}
}

// ✅ PREFERRED - Explicit mapping in calling code
CreateOrderData::from([
    'customerEmail' => $request->input('customer_email'),
]);

Why avoid case mappers:

  • Explicit mapping is clearer and more maintainable
  • Different API versions may have different field names
  • Transformers provide a single place to see all mappings
  • Avoids magic behavior that's hard to trace

Date Casting is Automatic

The package automatically casts date strings to Carbon or CarbonImmutable based on property types. Configure the expected date format in the package config.

// config/data.php
return [
    'date_format' => 'Y-m-d H:i:s',  // Or ISO 8601: 'Y-m-d\TH:i:s.u\Z'
];
class OrderData extends Data
{
    public function __construct(
        public CarbonImmutable $createdAt,   // Automatically cast from string
        public ?CarbonImmutable $shippedAt,  // Nullable dates work too
    ) {}
}

// ✅ Just pass the string - package handles casting
$data = OrderData::from([
    'createdAt' => '2024-01-15 10:30:00',
    'shippedAt' => null,
]);

Basic Structure

 */
        public Collection $items,
        public ShippingAddressData $shippingAddress,
        public BillingAddressData $billingAddress,
    ) {
        // Apply formatters in constructor
        $this->customerEmail = EmailFormatter::format($this->customerEmail);
    }
}

Key Patterns

Constructor Property Promotion

Always use promoted properties:

public function __construct(
    public string $name,
    public ?string $description,
    public bool $active = true,
) {}

Not:

public string $name;
public ?string $description;

public function __construct(string $name, ?string $description)
{
    $this->name = $name;
    $this->description = $description;
}

Type Everything

public string $email;                          // Required string
public ?string $phone;                         // Nullable string
public CarbonImmutable $createdAt;             // DateTime (immutable)
public OrderStatus $status;                    // Enum
public Collection $items;                      // Collection
public AddressData $address;                   // Nested DTO

Collections with PHPDoc

/** @var int[] */
public array $productIds;

/** @var Collection */
public Collection $items;

Nested Data Objects

class OrderData extends Data
{
    public function __construct(
        public CustomerData $customer,
        public ShippingAddressData $shipping,
        public BillingAddressData $billing,
        /** @var Collection */
        public Collection $items,
    ) {}
}

Formatters

Apply formatting in the constructor:

public function __construct(
    public string $email,
    public ?string $phone,
    public ?string $postcode,
) {
    $this->email = EmailFormatter::format($this->email);
    $this->phone = $this->phone ? PhoneFormatter::format($this->phone) : null;
    $this->postcode = $this->postcode ? PostcodeFormatter::format($this->postcode) : null;
}

Example formatter (app/Data/Formatters/EmailFormatter.php):

 */
        public Collection $items,
    ) {}

    public static function fromRequest(CreateOrderRequest $request): self
    {
        return self::from([
            'customerEmail' => $request->input('customer_email'),
            'notes' => $request->input('notes'),
            'status' => $request->input('status'),
            'items' => $request->input('items'),
        ]);
    }

    public static function fromModel(Order $order): self
    {
        return self::from([
            'customerEmail' => $order->customer_email,
            'notes' => $order->notes,
            'status' => $order->status,
            'items' => $order->items->toArray(),
        ]);
    }
}

When to use static methods on DTO:

  • Smaller applications with fewer DTOs
  • Simple transformations that don't need dedicated testing
  • When mapping is tightly coupled to a single DTO

When to use separate transformers:

  • Multiple external sources map to the same DTO
  • Complex transformation logic requiring extensive testing
  • Larger applications with clear separation of concerns

Model Casts

Cast model JSON columns to DTOs:

class Order extends Model
{
    protected function casts(): array
    {
        return [
            'metadata' => OrderMetadataData::class,
            'status' => OrderStatus::class,
        ];
    }
}

Usage:

// Store
$order = Order::create([
    'metadata' => $metadataData,  // OrderMetadataData instance
]);

// Retrieve
$metadata = $order->metadata;  // Returns OrderMetadataData instance

Naming Conventions

| Type | Pattern | Examples | |------|---------|----------| | Response DTOs | {Entity}Data | OrderData, UserData, ProductData | | Request DTOs | {Action}{Entity}Data | CreateOrderData, UpdateUserData | | Nested DTOs | {Descriptor}{Entity}Data | ShippingAddressData, OrderMetadataData |

Directory Structure

app/Data/
├── CreateOrderData.php
├── UpdateOrderData.php
├── OrderData.php
├── Concerns/
│   └── HasTestFactory.php
├── Formatters/
│   ├── EmailFormatter.php
│   ├── PhoneFormatter.php
│   └── PostcodeFormatter.php
└── Transformers/
    ├── PaymentDataTransformer.php
    ├── Web/
    │   └── OrderDataTransformer.php
    └── Api/
        └── V1/
            └── OrderDataTransformer.php

Usage in Controllers

Controllers transform requests to DTOs via transformers:

orders()->create([
                'customer_email' => $data->customerEmail,
                'notes' => $data->notes,
                'status' => $data->status,
            ]);
        });
    }
}

Transformers

For complex transformations (external APIs, webhooks, field mappings), use dedicated transformer classes.

[→ Complete guide: dto-transformers.md](references/dto-transformers.md)

// External system data
$data = PaymentDataTransformer::fromStripePaymentIntent($webhook['data']);

// Request with version-specific field names
$data = OrderDataTransformer::fromRequest($request);

Hierarchy of preference:

  1. Data::from($array) - Simple cases, direct mapping
  2. Data::fromRequest() - Static method on DTO for smaller apps
  3. Transformer::from*() - Complex transformations, multiple sources

Test Factories

Create hydrated DTOs for tests using the HasTestFactory trait.

[→ Complete guide: test-factories.md](references/test-factories.md)

Link DTOs to factories with PHPDoc:

/**
 * @see \Database\Factories\Data\CreateOrderDataFactory
 * @method static CreateOrderDataFactory testFactory()
 */
class CreateOrderData extends Data
{
    // ...
}

Usage:

$data = CreateOrderData::testFactory()->make();
$collection = OrderItemData::testFactory()->collect(count: 5);

// With overrides
$data = CreateOrderData::testFactory()->make([
    'customerEmail' => 'test@example.com',
]);

Testing DTOs

use App\Data\CreateOrderData;

it('can create DTO from array', function () {
    $data = CreateOrderData::from([
        'customerEmail' => 'test@example.com',
        'notes' => 'Test notes',
        'status' => 'pending',
    ]);

    expect($data)
        ->customerEmail->toBe('test@example.com')
        ->notes->toBe('Test notes');
});

it('formats email in constructor', function () {
    $data = new CreateOrderData(
        customerEmail: '  TEST@EXAMPLE.COM  ',
        notes: null,
        status: OrderStatus::Pending,
    );

    expect($data->customerEmail)->toBe('test@example.com');
});

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.