Skip to content

Laravel Integration

Complete guide for using Data Helpers with Laravel.

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
Terminal window
composer require event4u/data-helpers

Laravel automatically discovers the service provider. No configuration needed!

Terminal window
php artisan vendor:publish --tag=data-helpers-config

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);
}
}
  1. Laravel’s service container detects the Dto type hint
  2. Service provider creates an instance
  3. Request data is automatically passed to the Dto
  4. Validation runs automatically
  5. Controller receives the validated Dto
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);
}

Laravel provides seamless integration between DTOs and Eloquent models using the HasModel attribute.

$user = User::find(1);
$dto = UserDto::fromModel($user);
$dto = UserDto::fromArray($data);
$user = $dto->toModel(User::class);
$user->save();

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

$user = User::find(1);
$dto = UserDto::fromRequest($request);
// Update model with DTO data
$user->fill($dto->toArray());
$user->save();
try {
$dto = UserDto::validateAndCreate($request->all());
$user = User::create($dto->toArray());
} catch (ValidationException $e) {
return response()->json(['errors' => $e->errors()], 422);
}
class UserDto extends SimpleDto
{
public function __construct(
#[Required(message: 'Email is required')]
#[Email(message: 'Invalid email format')]
public readonly string $email,
) {}
}

Show property only when user is authenticated:

class UserProfileDto extends SimpleDto
{
public function __construct(
public readonly string $name,
#[WhenAuth]
public readonly ?string $email = null,
) {}
}

Show property only when user is guest:

#[WhenGuest]
public readonly ?string $registerPrompt = null;

Show property when user has permission:

#[WhenCan('edit-posts')]
public readonly ?string $editUrl = null;

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;

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"}}
return DtoResource::make($dto)->withoutWrapping();
// {"title":"Conference","startDate":"2024-01-15 10:30:00"}
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",...}]}
$paginator = Event::paginate(15);
$dtos = $paginator->map(fn($event) => EventDto::fromModel($event));
return new DtoResourceCollection($dtos);
// {"data":[...],"links":{...},"meta":{...}}
  • 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

The DtoResource uses SimpleEngine::toJsonArray() or LiteEngine::toJsonArray() internally, which:

  1. Converts the DTO to an array
  2. Formats DateTime objects according to #[DateTimeFormat] attributes
  3. Respects #[Hidden] and other serialization attributes

This ensures consistent serialization across your application, whether you use:

  • json_encode($dto) - Uses jsonSerialize()
  • $dto->toJson() - Direct JSON conversion
  • new DtoResource($dto) - Laravel Resource
Terminal window
php artisan make:dto UserDto

Creates 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,
) {}
}
Terminal window
php artisan dto:typescript

Generates TypeScript interfaces from your Dtos.

See also: Artisan Commands - Complete guide to all available Artisan commands