42

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

Volatil3
  • 14,253
  • 38
  • 134
  • 263
  • http://laravel.io/forum/01-19-2015-eloquent-postgres-and-the-json-datatype?page=1 – Rwd Sep 04 '15 at 08:36

3 Answers3

101

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

Martin Joiner
  • 3,529
  • 2
  • 23
  • 49
Helder Lucas
  • 3,273
  • 2
  • 21
  • 26
11

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'
        ];
    }
Roger
  • 1,142
  • 10
  • 6
  • 7
    You are correct that it should be array but sadly 'json' does actually work. It shouldn't because it encourages bad use of the casts property which exists to describe what you want to cast it _to_. Saying I want to cast a JSON field _to_ JSON is nonsense but lots of people are using it. This is symptomatic of a general misunderstanding around JSON anyway, the number of times I've seen PHP array variables called $jsonSomething. JSON is a string! Always will be, it's a form of _notation_ not an object or an array. – Martin Joiner Mar 22 '18 at 10:56
  • I use `$jsonSomething` to indicate that the string is expected to be a parseable JSON string. – Vladimir Hidalgo Feb 22 '21 at 02:23
2

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'
    ];
}
Md. Ziyed Uddin
  • 180
  • 1
  • 1
  • 10