4

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?

1
  • 2
    have you tried whereJsonContains('colors', 1)? assuming this is actually a json column Commented Feb 6, 2021 at 19:06

4 Answers 4

5

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();
Sign up to request clarification or add additional context in comments.

Comments

2

You can match it along with the quotes

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

2 Comments

Thank you, this works as well, thought I prefer the json approach since it is indeed a json column.
Yeah :) should also be faster than like I assume
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.