Laravel Eloquent JSON Contains, how to provide WhereIn logic (one of array values)

Viewed 13386

there is my code:

protected function room_count($room_count)
{
    $query = $this->builder
        ->whereJsonContains('rent_requests.rooms_count', $room_count);

    return $query;
}

There is my filter function. $room_count is array, and for example can be [2,4]. rent_requests.rooms_count is JSON array in MySQL, and it can be for example [2,3]. I need to filter this, to get this advert showed, but whereJSONContains expects that there will be 2 and 4, not 2 or 4. Is there any tricks to make this function work correctly ? Something like json contains whereIn ?) Sorry for my english, im really stuck on this, please help me :)

2 Answers

MySQL and PostgreSQL support whereJsonContains with multiple values:

So if you are using either of the database then you can pass $room_count as the second parameter

// Room Count Filter
protected function room_count($room_count)
{

    return $this->builder
        ->where(function($query) use($room_count){
     
            $query->whereJsonContains('rent_requests.rooms_count', $room_count[0]);
    
            for($i = 1; $i < count($room_count); $i++) {
               $query->orWhereJsonContains('rent_requests.rooms_count', $room_count[$i]);      
            }
    
            return $query;
      });
}

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

but @donkarnash function is slightly changed, here is the final version with this example for those who face the same problem

 // Room Count Filter
protected function room_count($room_count)
{
    return $this->builder
        ->where(function($query) use($room_count) {

            $query->whereJsonContains('rent_requests.rooms_count', $room_count[0]);

            info (count($room_count));

            for($i = 1; $i <= count($room_count) - 1; $i++) {
                $query->orWhereJsonContains('rent_requests.rooms_count', $room_count[$i]);
            }

            return $query;
        });
}
Related