Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]\"'))
like image 220
user3253002 Avatar asked Dec 05 '18 21:12

user3253002


2 Answers

The arrow operator doesn't work in arrays. Use this instead:

DB::table('emails')
   ->whereJsonContains('to', [['emailAddress' => ['address' => '[email protected]']]])
   ->get()
like image 70
Jonas Staudenmeir Avatar answered Nov 15 '22 15:11

Jonas Staudenmeir


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();
like image 32
Jenish Shrestha Avatar answered Nov 15 '22 14:11

Jenish Shrestha