cerbero90 / laravel-dto

Data Transfer Object (DTO) for Laravel

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

DTO to Laravel Eloquent Model

HeathNaylor opened this issue · comments

It appears that you can take a Laravel Eloquent Model into a DTO, but not a DTO into a Laravel Eloquent Model. Is this something that you plan to support in the future?

Hi @HeathNaylor, the single responsibility of DTOs is transferring data. If we added the functionality to turn a DTO into a model, then maybe in the future we would need to add more methods to transform DTOs into other classes and we would lose the SRP and clutter the class.

That said, a way to accomplish what you need is turning your DTO into an array and hydrate the model you want to instantiate:

// set mass-assignable properties
$user = new User($dto->toArray());

// set all properties
$user = User::forceFill($dto->toArray());

Please note that the above will work as long as property names in DTO and model match (DTO property names will be in snake case after the array conversion).

Gotcha, yea figured something along this line. Likely we should use a mapper pattern or builder to transfer between boundaries and maintain SRP.