Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 560
Volatil3 Avatar asked Sep 03 '15 08:09

Volatil3


People also ask

What is JSON in laravel?

Laravel JSON is a small package that makes encoding and decoding JSON a breeze with exceptions thrown on error immediately: A simple wrapper around json_encode() and json_decode() for catching any errors without executing json_last_error() .

What is JSON data type?

JSON (JavaScript Object Notation) is most widely used data format for data interchange on the web. JSON is a lightweight text based, data-interchange format and it completely language independent. It is based on a subset of the JavaScript programming language and it is easy to understand and generate.

What is JSON data type in MySQL?

MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.


2 Answers

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

like image 101
Helder Lucas Avatar answered Sep 19 '22 06:09

Helder Lucas


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'         ];     } 
like image 40
Roger Avatar answered Sep 21 '22 06:09

Roger