6

So I have a json column called settings in the table companies (which has a Laravel model called Company). That column may or may not contain an object called business_key. I try to return only the companies that contain this object. My query looks like this:

$owners = \Company::where('settings->business_key')->get();

I don't know how to make something like this work. I did not find anything Laravel specific for this. Thank you for your time and help!

1
  • If you have no default value for that column, it will be null in case of no business key. So, retrieve all column with not null business key Commented Jul 3, 2017 at 17:17

3 Answers 3

12

Assuming you are casting the field as an array in the model, you can treat it like other larval fields, so your query would be:

$owners = \Company::whereNotNull('settings->business_key')->get();
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, I have a problem too, in my case I have an JSON array of roles like ["user", "admin", "customer"] in this case how can I do a where clause for if a user is an admin?
So I figured it out, a simple Model::whereJsonContains["roles", "user"] fixed it...Yaaaay!
1

In the purpose to retrieve all not null data, you can try this :

$owners = \Company::whereRaw('JSON_EXTRACT(settings, "$.business_key") <> CAST("null" AS JSON)')->get();

Comments

0

Try this one,

$data = \Company::whereNotNull('setting')->get();

If setting column contains no object then value will be NULL, then above query gives all records with objects in setting column. See docs 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.