Validated DTO Package for Laravel
Published on by Paul Redmond
The Validated DTO package for Laravel provides Data Transfer Objects (DTO) with validation and type-casting. If you are using DTOs with your app to transfer data between systems, you'll likely also want to validate incoming request data as well. This package can centralize validation for DTO objects in the same way you validate request data:
class UserDTO extends ValidatedDTO{ /** * @return array */ protected function rules(): array { return [ 'name' => ['required', 'string'], 'email' => ['required', 'email'], 'password' => [ 'required', Password::min(8) ->mixedCase() ->letters() ->numbers() ->symbols() ->uncompromised(), ], ]; }}
I also like how you can create a DTO instance from the request object, like the following example:
public function store(Request $request): JsonResponse{ $dto = UserDTO::fromRequest($request);}
Here's a list of the package's main features from the most current documentation:
- Easily integrate it with your current project
- Data validation the same way you validate a Request
- Easily define custom validation messages
- Support for typed properties
- Type Casting out-of-the-box for your DTOs properties
- Support casting of nested data
- Easily create custom Type Casters for your own needs
Be sure to check out the documentation, which has set-up instructions, usage examples, and type-casting details. The source code is also available on GitHub at laravel-validated-dto.