0

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/

Fil
  • 8,225
  • 14
  • 59
  • 85

1 Answers1

1

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

DonUber
  • 60
  • 8