How to define and use JSON data type in Eloquent?

Volatil3 picture Volatil3 · Sep 3, 2015 · Viewed 43.3k times · Source

How can I define JSON data type that is provided in pgsql 9.4 in Laravel 5?

I need to define data type, storing and fetching data and so far could not find way to deal it in Laravel 5.1

Answer

Helder Lucas picture Helder Lucas · Sep 5, 2015

In your migrations you can do something like:

$table->json('field_name');

And in your model you add the field to the $casts property to instruct Eloquent to deserialize it from JSON into a PHP array:

class SomeModel extends Model
{
    protected $casts = [
        'field_name' => 'array'
    ];
}

Source: https://laravel.com/docs/5.1/eloquent-mutators#attribute-casting

Note: This is also relevant answer for Laravel 5.6