Laravel JSON Query

Laravel JSON Query

Laravel JSON Query


In Laravel, we can perform JSON queries using Eloquent, Laravel’s built-in ORM (Object-Relational Mapper), to work with your database. Below are some common JSON querying techniques in Laravel:


Let’s assume we have a users table with a JSON column named other_info storing additional user information. Here’s an example of how the table data might look like:

| id | name   | email             | other_info                                    |
| 1  | Alice  | | {"languages": ["English", "French"]}         |
| 2  | Bob    |   | {"languages": ["Spanish", "German"]}         |
| 3  | Charlie|| {"languages": ["English", "Italian"]}        |
| 4  | David  | | {"languages": ["French", "Chinese"]}         |

In this example:

  • Each row represents a user.
  • The other_info column stores JSON data, in this case, an object with a languages key, which contains an array of languages spoken by the user.
  • Users Alice and Charlie speak English among other languages.
  • User Bob speaks Spanish and German.
  • User David speaks French and Chinese.

We can then perform JSON queries on this data using Laravel’s Eloquent ORM as described in the previous response.


Basic JSON Field Query:

We can query JSON fields directly using Laravel‘s whereJsonContains method.

For example:

$users = User::whereJsonContains('meta->languages', 'English')->get();

This query will return all users whose meta JSON field contains the key languages with the value English.


Nested JSON Field Query:

If we need to query nested JSON fields, we can specify the nested key using dot notation.

For example:

$users = User::whereJsonContains('meta->', 'New York')->get();

This query will return all users whose meta JSON field has a nested object with contact object containing address object with city key having the value New York.


JSON Field Exists Check:

We can check for the existence of a specific key within a JSON field.

$users = User::whereJsonContains('meta', ['languages' => 'English'])->get();

This query will update the languages key within the meta JSON field of the user with ID 1 to French.

Remember to replace User with your actual Eloquent model name and adjust field names accordingly based on your database schema. Additionally, ensure that your database supports JSON querying (e.g., MySQL 5.7+ or PostgreSQL).


That’s all for today. See you in next one.


Check Out More Resources:

YouTube Channel:
WordPress Playlist:
Tools Playlist:

WordPress Tutorials:
Laravel Tutorials:
PHP Tutorials:
SQL Tutorials:
Various Tips:
Useful Tools:



#PHP #array #leetcode


That’s All. Feel free to knock me. Thanks.

Editorial Staff

A Learner and trying to share what I learned!