1. Go to this page and download the library: Download fab2s/laravel-dt0 library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
fab2s / laravel-dt0 example snippets
use fab2s\Dt0\Attribute\Rule;
use fab2s\Dt0\Attribute\Validate;
use fab2s\Dt0\Laravel\Dt0;
use fab2s\Dt0\Laravel\Validator;
#[Validate(Validator::class)]
class UserDto extends Dt0
{
#[Rule([' with validation (throws ValidationException on failure)
$user = UserDto::withValidation(
name: 'John Doe',
email: '[email protected]',
age: 30,
);
// Or create from various sources
$user = UserDto::from(['name' => 'John', 'email' => '[email protected]']);
$user = UserDto::fromJson('{"name":"John","email":"[email protected]"}');
// Immutable — this triggers a fatal error:
// $user->name = 'Jane'; // Error!
// Serialize
$user->toArray(); // ['name' => 'John', 'email' => '[email protected]', 'age' => 30]
$user->toJson(); // {"name":"John","email":"[email protected]","age":30}
use fab2s\Dt0\Attribute\Cast;
use fab2s\Dt0\Attribute\Rule;
use fab2s\Dt0\Attribute\Validate;
use fab2s\Dt0\Caster\DateTimeCaster;
use fab2s\Dt0\Caster\DateTimeFormatCaster;
use fab2s\Dt0\Laravel\Dt0;
use fab2s\Dt0\Laravel\Validator;
// 1. Define the DTO
#[Validate(Validator::class)]
class CreateOrderDto extends Dt0
{
#[Rule(['/ 2. In a controller — validate + hydrate in one step
public function store(Request $request): JsonResponse
{
$order = CreateOrderDto::withValidation(...$request->all());
// throws ValidationException with Laravel's error bag on failure
// 3. Use with Eloquent (model casts the DTO to JSON automatically)
$model = Order::create(['details' => $order]);
// 4. Read back — Eloquent casts JSON back to DTO
$model->refresh();
$model->details->product; // typed, immutable access
return response()->json($model);
}
// Option A: Validate in Dt0 (replaces Form Request)
$dto = CreateOrderDto::withValidation(...$request->all());
// Option B: Validate in Form Request, hydrate with Dt0
class CreateOrderRequest extends FormRequest
{
public function rules(): array { /* ... */ }
public function toDto(): CreateOrderDto
{
return CreateOrderDto::from($this->validated());
}
}
// In controller
public function store(CreateOrderRequest $request): JsonResponse
{
$order = $request->toDto();
// ...
}
use fab2s\Dt0\Laravel\Dt0;
class ProductDto extends Dt0
{
public readonly string $name;
public readonly float $price;
public readonly ?string $description;
}
// Named arguments
$dto = new ProductDto(name: 'Widget', price: 19.99, description: null);
// Static factory
$dto = ProductDto::make(name: 'Widget', price: 19.99);
// From array
$dto = ProductDto::fromArray(['name' => 'Widget', 'price' => 19.99]);
// From JSON
$dto = ProductDto::fromJson('{"name":"Widget","price":19.99}');
// Polymorphic (accepts array, JSON string, or instance)
$dto = ProductDto::from($mixedInput);
// Safe version (returns null instead of throwing)
$dto = ProductDto::tryFrom($mixedInput);
$dto->toArray(); // Array with objects preserved
$dto->toJsonArray(); // Array with jsonSerialize() called on nested objects
$dto->toJson(); // JSON string
(string) $dto; // Also returns JSON (Stringable)
use fab2s\Dt0\Attribute\Rule;
use fab2s\Dt0\Attribute\Rules;
use fab2s\Dt0\Attribute\Validate;
use fab2s\Dt0\Laravel\Dt0;
use fab2s\Dt0\Laravel\Validator;
#[Validate(
Validator::class,
new Rules(
name: new Rule('
#[Validate(Validator::class)]
#[Rules(
name: new Rule(['o extends Dt0
{
public readonly string $name;
public readonly string $email;
}
#[Validate(Validator::class)]
class UserDto extends Dt0
{
#[Rule([' public readonly string $email;
}
#[Validate(
Validator::class,
new Rules(name: new Rule('min:100')), // Lowest priority
)]
#[Rules(name: new Rule('min:50'))] // Middle priority
class UserDto extends Dt0
{
#[Rule('min:5')] // Highest priority — only min:5 is applied
public readonly string $name;
}
// Validates with min:5, NOT min:50 or min:100
$dto = UserDto::withValidation(name: 'hello'); // OK (5 chars)
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class Lowercase implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (strtolower($value) !== $value) {
$fail('The :attribute must be lowercase.');
}
}
}
#[Validate(Validator::class)]
class SlugDto extends Dt0
{
#[Rule(new Lowercase)]
public readonly string $slug;
}
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $casts = [
'shipping_address' => AddressDto::class,
'billing_address' => AddressDto::class . ':nullable',
];
}
$order = new Order;
// Set from array
$order->shipping_address = ['street' => '123 Main St', 'city' => 'NYC'];
// Set from JSON
$order->shipping_address = '{"street":"123 Main St","city":"NYC"}';
// Set from DTO instance
$order->shipping_address = AddressDto::from(['street' => '123 Main St', 'city' => 'NYC']);
// Access as DTO
echo $order->shipping_address->city; // 'NYC'
// Compare
$order->shipping_address->equals(AddressDto::from(['street' => '123 Main St', 'city' => 'NYC'])); // true
// Nullable handling
$order->billing_address = null; // OK (has :nullable modifier)
$order->shipping_address = null; // Throws NotNullableException
// Same caster for both directions
#[Cast(both: new EncryptedCaster)]
// Different casters per direction
#[Cast(in: new DateTimeCaster, out: new DateTimeFormatCaster('Y-m-d'))]
// Combine both: with in: or out: — chained as a CasterCollection (onion ordering)
// Input runs: both → in | Output runs: out → both
#[Cast(both: new EncryptedCaster, in: new SomeSanitizer)]
use fab2s\Dt0\Attribute\Cast;
use fab2s\Dt0\Laravel\Caster\CollectionOfCaster;
use fab2s\Dt0\Laravel\Dt0;
use Illuminate\Support\Collection;
class OrderDto extends Dt0
{
public readonly string $orderId;
#[Cast(in: new CollectionOfCaster(OrderItemDto::class))]
public readonly Collection $items;
}
// Each item in the array is cast to OrderItemDto
$order = OrderDto::from([
'orderId' => 'ORD-123',
'items' => [
['sku' => 'ABC', 'quantity' => 2],
['sku' => 'XYZ', 'quantity' => 1],
],
]);
$order->items; // Collection of OrderItemDto instances
use fab2s\Dt0\Attribute\Cast;
use fab2s\Dt0\Laravel\Caster\EncryptedCaster;
use fab2s\Dt0\Laravel\Dt0;
class UserDto extends Dt0
{
public readonly string $name;
#[Cast(both: new EncryptedCaster)]
public readonly string $apiKey;
}
// Initialize with plaintext — auto-detected and passed through
$user = UserDto::from([
'name' => 'John',
'apiKey' => 'my-secret-key',
]);
// Or load from encrypted storage — auto-detected and decrypted
$user = UserDto::from([
'name' => 'John',
'apiKey' => $encryptedValue,
]);
$user->apiKey; // Plaintext value
$user->toArray(); // ['name' => 'John', 'apiKey' => '...encrypted...']
// Recommended — reference config paths (resolved at runtime)
#[Cast(both: new EncryptedCaster(key: 'config:services.payment.encryption_key'))]
public readonly string $paymentToken;
// Both key and cipher from config
#[Cast(both: new EncryptedCaster(
key: 'config:services.payment.encryption_key',
cipher: 'config:services.payment.cipher',
))]
public readonly string $secret;
// Serialize complex values (arrays, objects)
new EncryptedCaster(serialize: true)
// Direct key/cipher (for programmatic usage only — never hardcode in attributes)
new EncryptedCaster(key: 'base64:...', cipher: 'AES-128-CBC')