jaetoole/castable-dto

Cast Eloquent Fields To Standard PHP 8 DTOs (Alpha).

1.0.0 2022-07-05 14:39 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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.

Installation

You can install the package via composer:

composer require jaetoole/castable-dto

It's as simple as that!

Usage

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.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.