Home > OS >  Laravel Eloquent Collection filter by pivot id
Laravel Eloquent Collection filter by pivot id

Time:02-22

This is my Apartment integrated with services

"id": 26,
"user_id": 1,
"title": "SAN MARINO",
"slug": "san-marino",
"rooms": 1,
"bathrooms": 1,
"beds": 1,
"squared_meters": 12,
"address": "San Marino, Carpi",
"latitude": "44.80924",
"longitude": "10.91565",
"image": "apartment_image/BMRQZSXLdWviqDwmHgqLzrmzG1hJzJGOq7DujnRB.jpg",
"is_visible": 1,
"floor": 1,
"price": 120,
"description": "2",
"created_at": "2022-02-21T21:41:53.000000Z",
"updated_at": "2022-02-21T21:41:53.000000Z",
"services": [
{
"id": 2,
"name": "Posto Macchina",
"slug": "posto-macchina",
"created_at": "2022-02-21T08:59:53.000000Z",
"updated_at": "2022-02-21T08:59:53.000000Z",
"pivot": {
"apartment_id": 26,
"service_id": 2
}
}
]
}

I use to filter my collection( $apartment_list = ApartmentResource::collection(Apartment::with(['services'])->get());)

using multiple WHERE, like this: $apartment_list = $apartment_list->where('rooms', '>=', $rooms);

How can i filter my Apartment refering to the pivot column service_id or services[id]?

CodePudding user response:

There is filter method for the collection. You may create a callback for a single apartament and filter in any way you want:

$apartment_list->filter(function ($apartament) {
   // ...
});

CodePudding user response:

you can use try with this:

$serviceId = value_of_service_id;

$apartment_list = ApartmentResource::collection(Apartment:: whereHas('services', function ($q) use ($serviceId) {
    $q->where('service_id', $serviceId);
})->get());
  • Related