โœ…
Laravel Validated DTO
View on GitHub
  • โœ…Validated DTO for Laravel
  • ๐Ÿš€Getting Started
    • Installation
    • Configuration
    • Upgrade Guide
    • Changelog
  • ๐Ÿ˜ŽThe Basics
    • Generating DTOs
    • Defining DTO Properties
    • Defining Validation Rules
    • Creating DTO Instances
    • Accessing DTO Data
    • Defining Default Values
    • Transforming DTO Data
    • Mapping DTO properties
    • Simple DTOs
    • Resource DTOs
    • Wireable DTOs
    • Lazy Validation
    • Generating TypeScript Definitions
  • ๐ŸŽจCustomize
    • Custom Error Messages and Attributes
    • Custom Exceptions
  • ๐ŸงชType Casting
    • Introduction
    • Available Types
    • Create Your Own Type Cast
    • Casting Eloquent Model properties to DTOs
Powered by GitBook
On this page

Was this helpful?

  1. The Basics

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
PreviousSimple DTOsNextWireable DTOs

Last updated 1 year ago

Was this helpful?

๐Ÿ˜Ž