Fil
Fil

Reputation: 8873

Making a query on a table that has json field and postgresql database and laravel

I have a table the has column that contains a json field and postgresql as database storage containing this example:

{"wants_newsletter": "true", "favorite_color": "red"}

If I query on laravel like:

$model = Model::where('column->favorite_color', 'red')->first();

I can get the row successfully and now can do like

$id = $model->id;

But when on the same column has this kind of json structure

{"wants_newsletter": ["true"], "favorite_color": ["red","blue"]}

If I query on laravel like:

$model = Model::where('column->favorite_color[0]', 'red')->first();

I get $model that is null, which mean I did not fetch a row.

How to do it in laravel?

My resources find when searching are these: How can I make query where json column in the laravel? https://mattstauffer.com/blog/new-json-column-where-and-update-syntax-in-laravel-5-3/

Upvotes: 0

Views: 814

Answers (1)

DonUber
DonUber

Reputation: 60

I think what you are looking for is:

->whereJsonContains('column->favorite_color', 'red')->first();

See https://laravel.com/docs/8.x/queries#json-where-clauses

Upvotes: 1

Related Questions