PHP code example of kfoobar / laravel-dto

1. Go to this page and download the library: Download kfoobar/laravel-dto 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/ */

    

kfoobar / laravel-dto example snippets


use Carbon\CarbonImmutable;
use KFoobar\Data\DataTransferObject;

class PostData extends DataTransferObject
{
    public int $id;
    public string $title;
    public string $status = 'draft';
    public array $tags = [];
    public ?CarbonImmutable $published_at = null;
}

$postData = PostData::fromArray([
    'id' => '42',
    'title' => 'Example post',
    'published_at' => '2026-10-05T12:30:00+02:00',
]);

$postData->id;           // 42
$postData->status;       // 'draft'
$postData->published_at; // CarbonImmutable instance

$postData = new PostData(['id' => 42, 'title' => 'Example post']);
$postData = PostData::fromArray(['id' => 42, 'title' => 'Example post']);
$postData = PostData::fromRequest($request);
$postData = PostData::fromModel($post);

$postData = PostData::fromArray($request->validated());

class OptionalData extends DataTransferObject
{
    public ?string $note = null;
    public array $tags = [];
}

class IdentifierData extends DataTransferObject
{
    public int|string $id;
    public int|float $amount;
}

$data = IdentifierData::fromArray(['id' => '0042', 'amount' => '4.5']);

$data->id;     // '0042', preserving the matching string type
$data->amount; // 4.5