Blog Detail

28

Dec
Automatically Cast JSON Columns to PHP Objects in Laravel  cover image

arrow_back Automatically Cast JSON Columns to PHP Objects in Laravel

Have you ever wanted to cast your JSON columns to a value object?
Now you can do it because Jess Archer comes up with a package called laravel-castable-data-transfer-object which automatically casts an array (associative or numeric) to JSON, and back again. This package gives you an extended version of Spatie’s DataTransferObject class, called CastableDataTransferObject.
Under the hood, it implements Laravel’s Castable interface with a Laravel custom cast that handles serializing between the DataTransferObject (or a compatible array) and your JSON database column.

For an in-depth explanation of what it’s actually doing and the motivation behind it, check out the blog post of Jess Archer here.

Installation

You can install this package via composer by running this command in the terminal:

composer require jessarcher/laravel-castable-data-transfer-object

Usage

1. Create your CastableDataTransferObject

Check out the readme for Spatie’s data transfer object package to find out more about what their DataTransferObject class can do.

namespace App\Values;

use JessArcher\CastableDataTransferObject\CastableDataTransferObject;

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

(Note: I like to put these in App\Values because I’m using them as a value object and not just a plain DTO. Feel free to put it anywhere you like!)

2. Configure your Eloquent attribute to cast to it:

Note that this should be a jsonb or json column in your database schema.

namespace App\Models;

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

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

And that’s it! 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.

$user = User::create([
    // ...
    'address' => [
        'street' => '1640 Riverside Drive',
        'suburb' => 'Hill Valley',
        'state' => 'California',
    ],
])

$residents = User::where('address->suburb', 'Hill Valley')->get();

But the best part is that you can decorate your class with domain-specific methods to turn it into a powerful value object.

$user->address->toMapUrl();

$user->address->getCoordinates();

$user->address->getPostageCost($sender);

$user->address->calculateDistance($otherUser->address);

echo (string) $user->address;

Controlling serialization

You may provide the caster with flags to be used for serialization by adding the CastUsingJsonFlags attribute to your object:

use JessArcher\CastableDataTransferObject\CastableDataTransferObject;
use JessArcher\CastableDataTransferObject\CastUsingJsonFlags;

#[CastUsingJsonFlags(encode: JSON_PRESERVE_ZERO_FRACTION)]
class Address extends CastableDataTransferObject {}

This package is very handy, You can visit more details about this package and get the source code on Github.

Published at : 28-12-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project