Do you want to harness the power of DTOs with Eloquent? If so, this is the package for you. Using PHP 8 DTOs, you can now cast any array/json eloquent column to a DTO. This package is inspired by this awesome package.
You can install the package via composer:
composer require jaetoole/castable-dto
It's as simple as that!
Imagine we have a Data Transfer Object like the below:
<?php
class MyDto
{
public function __construct(
public string $myField
public int $mySecondField
) {
}
}
That's good but how would we populate this from an Eloquent array or JSON object?
First off, let's extend the CastableDto
class.
<?php
class MyDto extends \JaeToole\CastableDto\CastableDto
{
public function __construct(
public string $myField
public int $mySecondField
) {
}
}
Then, in your model, you can specify the following:
protected $casts => [
'myArrayField' => MyDto::class
]
Then, when fetching or storing your myArrayField
, it will be automatically converted to your Data Transfer Object.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.