Volatil3
Volatil3

Reputation: 15008

How to define and use JSON data type in Eloquent?

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

Upvotes: 45

Views: 83663

Answers (3)

Md. Ziyed Uddin
Md. Ziyed Uddin

Reputation: 212

For Object to JSON casting

class YourModel extends Model
{
    protected $casts = [
        'table_column_name' => 'object'
    ];
}

For Array to JSON casting

 class YourModel extends Model
{
    protected $casts = [
        'table_column_name' => 'array'
    ];
}

Upvotes: 2

Helder Lucas
Helder Lucas

Reputation: 3343

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

Upvotes: 106

Roger
Roger

Reputation: 1550

According to Laravel documentation, 'json' is not one of the casting available types. https://laravel.com/docs/5.1/eloquent-mutators

You should use 'array' instead:

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

Upvotes: 12

Related Questions