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:

1namespace App\Values;
3use JessArcher\CastableDataTransferObject\CastableDataTransferObject;
5class Address extends CastableDataTransferObject
7 public string $street;
8 public string $suburb;
9 public string $state;

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

1namespace App\Models;
3use App\Values\Address;
4use Illuminate\Database\Eloquent\Model;
6class User extends Model
8 protected $casts = [
9 'address' => Address::class,
10 ];

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:

1// Custom helper method
4// Convert to a string
5echo (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.

Laravel News Partners