Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martinro's avatar

How to query nested json

Good day all!

I'm having difficulties querying a json column. This is what's stored in the field:

[
  {
    "key": "NXtQTr1wa6XCGjfH",
    "layout": "meta_data",
    "attributes": {
      "meta_title": "Testing",
      "meta_robots": "index, follow",
    }
  }
]

This works

$pages = \DB::table('pages')
            ->whereJsonContains('meta_data', ['key' => 'NXtQTr1wa6XCGjfH'])
            ->get();

This doesn't

$pages = \DB::table('pages')
            ->whereJsonContains('meta_data->attributes', ['meta_robots' => 'index, follow'])
            ->get();

it's for sure because of the structure of the json, but can't figure out how to access the nested attributes. Any help is much appreciated.

0 likes
5 replies
martinro's avatar

Nope, unfortunately that doesn't work

kingmaker_bgp's avatar

I think you have to use the normal array of expected values as the second argument to whereJsonContains

$pages = \DB::table('pages')
            ->whereJsonContains('meta_data->attributes->meta_robots', 'index, follow')
            ->get();

Documentation

martinro's avatar

Nope, unfortunately that doesn't work

martinro's avatar
martinro
OP
Best Answer
Level 4

Slept over it and came up with this working:

$pages = \DB::table('pages')
            ->whereJsonContains('meta_data', [['attributes' => ['meta_robots' => 'index, follow']]])
            ->get();

Thanks all for the help!

1 like

Please or to participate in this conversation.