Laravel Castable Data Transfer Object

Laravel Castable Data Transfer Object

Laravel Castable Data Transfer Object is a package by Jess Archer for casting JSON columns in the database to a value object. This package expands on Spatie’s data-transfer-object package with the CastableDataTransferObject class, which implements Laravel’s “castable” interface using custom Eloquent cast types (added in Laravel 7).

Here’s an example of what an address object from a JSON column might look like as a castable object:

namespace App\Values;

use JessArcher\CastableDataTransferObject\CastableDataTransferObject;

class Address extends CastableDataTransferObject
{
    public string $street;
    public string $suburb;
    public string $state;
}

When combined with a model’s casts, you can configure it like so:

namespace App\Models;

use App\Values\Address;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'address' => Address::class,
    ];
}

According to the project’s readme, the above is all you need to start transferring data in and out of the JSON column:

You can now pass either an instance of your Address class or even just an array with a compatible structure. It will automatically be cast between your class and JSON for storage, and the data will be validated on the way in and out.

One benefit of using a Value object is that you can define custom methods around the cast, meaning you can do cool things like implementing the __toString() method or a custom helper:

// Custom helper method
$user->address->getCoordinates();

// Convert to a string
echo (string) $user->address;

Learn More

You can learn more about this package, get full installation instructions, and view the source code on GitHub. Jess goes into further detail on her blog about the ideas behind this package with more information about how it works under the hood.

Filed in: News

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Laravel Senior Developer
Remote, Canada Only
BeMo Academic Consulting
Senior Fullstack Developer / Architect (w/m/d)
Remote / Munich - Germany
envivo.select GmbH
Medior full stack developer (Laravel)
Deventer (or remote) in the Netherlands, Dutch speaking required.
MSML B.V.
Senior Full Stack PHP Developer (Laravel)
Remote
MAPPEN
Senior Laravel Developer
Remote
ACTO