laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

MIT License

Downloads
193.6K
Stars
641
Committers
18

Bot releases are visible (Hide)

laravel-validated-dto - ResourceDTO and Wireable Trait

Published by WendellAdriel over 1 year ago

Changes

  • Added a new ResourceDTO class that you can use to wrap, type and transform your API responses
  • Added a new Wireable trait that you can use to turn any DTOs into Wireable DTOs to use with Laravel Livewire

Docs for changes

Resource DTOs

If you want to use DTOs to wrap, type and transform your API responses, you can use the ResourceDTO class.
This class will have the same features as the SimpleDTO class and will implement the Illuminate\Contracts\Support\Responsable interface:

class UserResourceDTO extends ResourceDTO
{
    public string $name;

    public string $email;

    public int $age;

    // Your DTO methods...
}

Then you can return your DTOs from your controllers:

class UserController extends Controller
{
    public function show(int $id)
    {
        return UserResourceDTO::fromModel(User::findOrFail($id));
    }
}

You can also return a collection/list of your DTOs as a response using the ResourceDTO::collection() method:

class UserController extends Controller
{
    public function index()
    {
        return UserResourceDTO::collection(User::all());
    }
}

This way every item in the collection will be converted to a UserResourceDTO instance before sending
the response to the client, using all the typing, casting and mapping features of your DTO class.

To generate a ResourceDTO you can use the --resource flag:

php artisan make:dto UserResourceDTO --resource

Wireable DTOs

If you're using Laravel Livewire, you can turn your DTOs into wireable DTOs
by adding the WendellAdriel\ValidatedDTO\Concerns\Wireable trait to your DTOs:

class UserDTO extends ValidatedDTO
{
    use Wireable;

    // Your DTO code...
}