'Search in Json column with Laravel

In my emails table, I have a column named To with column-type Json. This is how values are stored:

[
    {
        "emailAddress": {
            "name": "Test", 
            "address": "[email protected]"
        }
    }, 
    {
        "emailAddress": {
            "name": "Test 2", 
            "address": "[email protected]"
        }
    }
]

Now I want a collection of all emails sent to "[email protected]". I tried:

DB::table('emails')->whereJsonContains('to->emailAddress->address', '[email protected]')->get();

(see https://laravel.com/docs/5.7/queries#json-where-clauses) but I do not get a match. Is there a better way to search using Laravel (Eloquent)?

In the debugbar, I can see that this query is "translated" as:

select * from `emails` where json_contains(`to`->'$."emailAddress"."address"', '\"[email protected]\"'))


Solution 1:[1]

I haven't used the json column but as the documentation refers, the below code should work fine.

DB::table('emails')
  ->where('to->emailAddresss->address','[email protected]')
  ->get();

Solution 2:[2]

In case to store array in json format. And just have an array list of IDs, I did this.

items is the column name and $item_id is the term I search for

// $item_id = 2
// items = '["2","7","14","1"]'
$menus = Menu::whereJsonContains('items', $item_id)->get();

Solution 3:[3]

Checkout the Laravel API docs for the whereJsonContains method https://laravel.com/api/8.x/Illuminate/Database/Query/Builder.html#method_whereJsonContains

Solution 4:[4]

You can use where clause with like condition

DB::table('emails')->where('To','like','%[email protected]%')->get();

Alternatively, if you have Model mapped to emails table names as Email using Eloquent

Email::where('To','like','%[email protected]%')->get(); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jenish Shrestha
Solution 2 Nasser Ali Karimi
Solution 3 humaneguy
Solution 4 user3253002