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
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() .
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.
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.
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
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' ]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With