Laravel Integration
Complete guide for using Data Helpers with Laravel.
Introduction
Section titled “Introduction”Data Helpers provides seamless Laravel integration:
- ✅ Automatic Service Provider - Zero configuration
- ✅ Controller Injection - Automatic validation & filling
- ✅ Eloquent Integration - fromModel(), toModel()
- ✅ Request Validation - validateAndCreate()
- ✅ Artisan Commands - make:dto, dto:typescript
- ✅ Laravel Attributes - WhenAuth, WhenGuest, WhenCan, WhenRole
- ✅ API Resources - Replace Laravel Resources
Installation
Section titled “Installation”composer require event4u/data-helpersLaravel automatically discovers the service provider. No configuration needed!
Publish Configuration (Optional)
Section titled “Publish Configuration (Optional)”php artisan vendor:publish --tag=data-helpers-configController Injection
Section titled “Controller Injection”Automatic Validation & Injection
Section titled “Automatic Validation & Injection”Type-hint your Dto in controller methods:
use App\Dtos\UserRegistrationDto;use Illuminate\Http\JsonResponse;
class UserController extends Controller{ public function register(UserRegistrationDto $dto): JsonResponse { // $dto is automatically validated and filled with request data $user = User::create($dto->toArray());
return response()->json($user, 201); }}How It Works
Section titled “How It Works”- Laravel’s service container detects the Dto type hint
- Service provider creates an instance
- Request data is automatically passed to the Dto
- Validation runs automatically
- Controller receives the validated Dto
Manual Creation
Section titled “Manual Creation”public function register(Request $request): JsonResponse{ $dto = UserRegistrationDto::fromRequest($request); $dto->validate(); // Throws ValidationException on failure
$user = User::create($dto->toArray()); return response()->json($user, 201);}Eloquent Integration
Section titled “Eloquent Integration”Laravel provides seamless integration between DTOs and Eloquent models using the HasModel attribute.
From Eloquent Model
Section titled “From Eloquent Model”$user = User::find(1);$dto = UserDto::fromModel($user);To Eloquent Model
Section titled “To Eloquent Model”$dto = UserDto::fromArray($data);$user = $dto->toModel(User::class);$user->save();Using HasModel Attribute
Section titled “Using HasModel Attribute”Link your DTO to an Eloquent model to avoid passing the class name:
use event4u\DataHelpers\SimpleDto;use event4u\DataHelpers\SimpleDto\Attributes\HasModel;
#[HasModel(User::class)]class UserDto extends SimpleDto{ public function __construct( public readonly int $id, public readonly string $name, public readonly string $email, ) {}}
// No need to specify model class - it's resolved from the attribute$dto = UserDto::fromModel($user);$newUser = $dto->toModel(); // User::class is automatically resolved$newUser->save();📖 HasModel Attribute Details - Similar pattern to HasObject for plain PHP
Update Existing Model
Section titled “Update Existing Model”$user = User::find(1);$dto = UserDto::fromRequest($request);
// Update model with DTO data$user->fill($dto->toArray());$user->save();Request Validation
Section titled “Request Validation”Validate and Create
Section titled “Validate and Create”try { $dto = UserDto::validateAndCreate($request->all()); $user = User::create($dto->toArray());} catch (ValidationException $e) { return response()->json(['errors' => $e->errors()], 422);}Custom Validation Messages
Section titled “Custom Validation Messages”class UserDto extends SimpleDto{ public function __construct( #[Required(message: 'Email is required')] #[Email(message: 'Invalid email format')] public readonly string $email, ) {}}Laravel-Specific Attributes
Section titled “Laravel-Specific Attributes”WhenAuth
Section titled “WhenAuth”Show property only when user is authenticated:
class UserProfileDto extends SimpleDto{ public function __construct( public readonly string $name,
#[WhenAuth] public readonly ?string $email = null, ) {}}WhenGuest
Section titled “WhenGuest”Show property only when user is guest:
#[WhenGuest]public readonly ?string $registerPrompt = null;WhenCan
Section titled “WhenCan”Show property when user has permission:
#[WhenCan('edit-posts')]public readonly ?string $editUrl = null;WhenRole
Section titled “WhenRole”Show property when user has role:
#[WhenRole('admin')]public readonly ?array $adminPanel = null;
// Multiple roles (OR logic)#[WhenRole(['admin', 'moderator'])]public readonly ?array $moderationPanel = null;API Resources
Section titled “API Resources”DtoResource
Section titled “DtoResource”Data Helpers provides DtoResource and DtoResourceCollection classes that work like Laravel’s JsonResource but with automatic DateTimeFormat support.
use event4u\DataHelpers\SimpleDto;use event4u\DataHelpers\SimpleDto\Attributes\DateTimeFormat;use event4u\DataHelpers\Frameworks\Laravel\Resources\DtoResource;
class EventDto extends SimpleDto{ public function __construct( public readonly string $title,
#[DateTimeFormat('Y-m-d H:i:s')] public readonly DateTime $startDate, ) {}}
// In controller$dto = new EventDto('Conference', new DateTime('2024-01-15 10:30:00'));
return new DtoResource($dto);// {"data":{"title":"Conference","startDate":"2024-01-15 10:30:00"}}Without Wrapping
Section titled “Without Wrapping”return DtoResource::make($dto)->withoutWrapping();// {"title":"Conference","startDate":"2024-01-15 10:30:00"}DtoResourceCollection
Section titled “DtoResourceCollection”use event4u\DataHelpers\Frameworks\Laravel\Resources\DtoResourceCollection;
$dtos = [ new EventDto('Conference', new DateTime('2024-01-15 10:30:00')), new EventDto('Workshop', new DateTime('2024-01-16 14:00:00')),];
return new DtoResourceCollection($dtos);// {"data":[{"title":"Conference",...},{"title":"Workshop",...}]}With Pagination
Section titled “With Pagination”$paginator = Event::paginate(15);$dtos = $paginator->map(fn($event) => EventDto::fromModel($event));
return new DtoResourceCollection($dtos);// {"data":[...],"links":{...},"meta":{...}}Features
Section titled “Features”- ✅ Automatic DateTimeFormat Support - DateTime objects are formatted according to
#[DateTimeFormat]attributes - ✅ SimpleDto and LiteDto Support - Works with both DTO types
- ✅ Laravel Resource Features - Full support for wrapping, pagination, etc.
- ✅ Type-Safe - Full PHPStan level 9 support
How It Works
Section titled “How It Works”The DtoResource uses SimpleEngine::toJsonArray() or LiteEngine::toJsonArray() internally, which:
- Converts the DTO to an array
- Formats DateTime objects according to
#[DateTimeFormat]attributes - Respects
#[Hidden]and other serialization attributes
This ensures consistent serialization across your application, whether you use:
json_encode($dto)- UsesjsonSerialize()$dto->toJson()- Direct JSON conversionnew DtoResource($dto)- Laravel Resource
Artisan Commands
Section titled “Artisan Commands”Generate Dto
Section titled “Generate Dto”php artisan make:dto UserDtoCreates app/Dtos/UserDto.php:
<?php
namespace App\Dtos;
use event4u\DataHelpers\SimpleDto;
class UserDto extends SimpleDto{ public function __construct( public readonly string $name, public readonly string $email, ) {}}Generate TypeScript
Section titled “Generate TypeScript”php artisan dto:typescriptGenerates TypeScript interfaces from your Dtos.
See also: Artisan Commands - Complete guide to all available Artisan commands