devopix
devopix

Reputation: 187

Laravel 8.x Where Json Search In Array

My DB column field ("colors") contains an array structured like this:

["1","2","3"]

My current query look like this, simplified for better example:

$value = '1';

$cards = Card::query()
->where('colors', 'like', '%' . $value . '%')
->get();

The problem is, it fetches data from other columns, for example ["5","8","13"] will match "13" instead of the strict $value, which should be "1".

How do I write this query the correct way?

Upvotes: 4

Views: 11513

Answers (4)

Akbarali
Akbarali

Reputation: 904

I had a multilingual Slug. I got it with this code

$category = CategoryModel::query()->whereJsonContains('slug->' . app()->getLocale(), $category)->first();
dd($category->toArray());

Result: enter image description here

DB enter image description here

Upvotes: 0

Mehravish Temkar
Mehravish Temkar

Reputation: 4365

You can match it along with the quotes

$cards = Card::query()
->where('colors', 'like', '%"' . $value . '"%')
->get();

Upvotes: 2

Jignesh Joisar
Jignesh Joisar

Reputation: 15105

used whereJsonContains Method here

value like this then do like that ["1","2","3"]

$cards = Card::query()
->whereJsonContains('colors', '1')
->get();

if value like that [1,2,3] then used like that

$cards = Card::query()
    ->whereJsonContains('colors', 1)
    ->get();

Upvotes: 5

NIKHIL NEDIYODATH
NIKHIL NEDIYODATH

Reputation: 2932

You can query the JSON array fields as follows

$cards = Card::query()
->whereNotNull("colors->$value")
->get();

The above query will return cards having colour in the $value

Upvotes: 0

Related Questions