Menü schliessen
Created: July 7th 2023
Last updated: July 7th 2023
Categories: IT Development,  IT Knowledge,  Laravel,  Php
Author: LEXO

How to query in Laravel multilevel (nested) json() column without unique keys

Tags:  guide,  Laravel,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Let's say that we have a table column called json_data and it contains following values in first two rows:

  1. first row
    [
        {
            "data": {
                "id": "1"
            },
           "name": "some-id"
        },
        {
            "data": {
                "test-status": "ok"
            },
            "other-name": "test"
        }
    ]
  2. second row
    [
        {
            "data": {
                "id": "2"
            },
           "name": "some-other-id"
        },
        {
            "data": {
                "test-status": "ok"
            },
            "name": "other-test"
        },
        {
            "random": {
                "random-key": 2
            }
        }
    ]

If we want to find all results where data key contains an array with a key test-status and it's value is equal to ok then we need to write a query like this:

Model::whereJsonContains('json_data', ['data' => ['test-status' => 'ok']])->get();