PHP code example of sinmiloluwa / laravel-dto-mapper

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

    

sinmiloluwa / laravel-dto-mapper example snippets


use App\Models\User;
use Sinmiloluwa\LaravelDtoMapper\Attributes\Cast;
use Sinmiloluwa\LaravelDtoMapper\Attributes\MapFrom;
use Sinmiloluwa\LaravelDtoMapper\Traits\MapsAttributes;

#[MapFrom(User::class)]
class UserData
{
    use MapsAttributes;

    public string $name;

    public ?string $nickname;

    public string $role = 'member';

    #[Cast('int')]
    public int $age;

    #[Cast('bool')]
    public bool $active;
}

$dto = UserData::from(User::find(1));
$dto = UserData::from(['name' => 'Jane', 'age' => '25', 'active' => '1']);

$dto->toArray(); // ['name' => 'Jane', 'nickname' => null, 'role' => 'member', 'age' => 25, 'active' => true]

use Sinmiloluwa\LaravelDtoMapper\Exceptions\DtoMappingException;

try {
    UserData::from(['age' => 30]);
} catch (DtoMappingException $e) {
    // Property [name] on [UserData] is missing from the source and is not nullable.
}