Amit
Amit
May 8 · 1 min read

JSON Column in Laravel

Laravel provides an efficient way to handle JSON column in the table with its magical tool Eloquent. Few tips and tricks what I have learned:

  1. Casts your JSON data to an array:
    Do you know, it’s possible to insert, update and fetch array values directly into/from JSON column in the table with the help of Eloquent.
    E.g. Model:
    protected $casts = [
    ‘json_column’ => ‘array’
    ];

Now, whenever you fetch a Model object, ‘json_column’ will be casted as an array.

2. Query JSON column like a boss:
Do you know, It’s quite easy to query JSON column with the help of eloquent. First cast json_column to an array in the model, so the model knows how to deal with the column, whether to be an array or JSON.
E.g. Model:
protected $casts = [
‘json_column’ => ‘array’
];

Let’s say, json_column contains [1,2,3], now, one can easily do something like:Model::whereJsonContains('json_column', 1)->get()

Happy Coding