Search code examples
laravelpostgresqleloquentjsonblaravel-5.6

Laravel 5.6. JSONb column. Count array


I'm using JSONb columns of the PostgreSQL.

I have such an array in my data column

{
    myKey: []
}

How can I check through Laravel, if this array is empty or not?

Something like

MyModel::where('data->myKey'...)

Solution

  • You have to use a raw statement:

    MyModel::whereRaw("json_array_length((data->'myKey')::json) > 0")
    

    In Laravel 5.7.2 you can use whereJsonLength():

    MyModel::whereJsonLength('data->myKey', '>', 0)