Laravel Castable Data Transfer Object


October 29th, 2020


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

// 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:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.