Hello everyone, I'm a beginner in the coding world and I'm facing a problem I don't know how to solve.
I'm building a simplified replica of AirBnB, I give the user the possibility to select some services to have a list of apartments with those services.
I have an Apartments table and a Services table in my db, in between them there's a many to many relation, so there's the pivot table with apartment_id and service_id.
The question is: how do I retrieve from the db only the apartments with the selected services? (and obviously also the apartments with more services)
There are some of the solutions I have found on the Internet:
$test = Apartment::whereHas('services', function($q) use ($userServices) {
$q->whereIn('services.id', $userServices);
})->get();
foreach($userServices as $userService) {
$query = Apartment::whereHas('services', function($q) use($userService){
$q->where('apartment_service.service_id', $userService);
});
}
$test2 = $query->get();
Both of them do not work properly, because they retrieve also apartments that don't have the selected services.
Does anyone know how to do it?