Install via Composer:
composer require dreadnip/smart-dto-bundle
Publish the bundle configuration (if needed):
php artisan vendor:publish --provider="Dreadnip\SmartDtoBundle\SmartDtoServiceProvider"
First Use Case: Create a DTO class extending SmartDto trait (replacing the previous abstract class approach):
use Dreadnip\SmartDtoBundle\SmartDto;
class UserDto extends SmartDto
{
// Automatically handles casting, validation, and hydration
}
Replace abstract class inheritance with the new SmartDto trait:
// Old (deprecated)
class UserDto extends AbstractSmartDto { ... }
// New (recommended)
class UserDto extends SmartDto { ... }
Automatic Casting: Define $casts property for type conversion:
protected $casts = [
'is_active' => 'boolean',
'created_at' => 'datetime'
];
Validation: Use $rules for model-like validation:
protected $rules = [
'email' => 'required|email',
'age' => 'integer|min:18'
];
Hydration: Map request data automatically:
$dto = UserDto::fromRequest($request);
Service Integration: Bind DTOs in service providers:
$this->app->bind(UserDto::class, function () {
return new UserDto();
});
AbstractSmartDto class is now deprecated. Use SmartDto trait instead.Arrayable or Jsonable).$dto->errors() for validation failures.dd($dto->getOriginal()) to inspect raw data before casting.Custom Casting: Override castAttribute() for custom logic:
public function castAttribute($key, $value)
{
if ($key === 'custom_field') {
return strtoupper($value);
}
return parent::castAttribute($key, $value);
}
Dynamic Rules: Implement getRules() for dynamic validation:
public function getRules()
{
return array_merge($this->rules, ['dynamic_field' => 'required_if:other_field,1']);
}
Mass Assignment: Use $guarded to protect attributes:
protected $guarded = ['password'];
How can I help you explore Laravel packages today?