Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saaz's avatar
Level 5

Laravel Eloquent hasMany Relationship select specific ids

I am struggling to find the Person who has the exact specified cars in the following scenario.

Person Table

id | name
1  | Sachin
2  | Rahul
3  | Saurav

Cars Table

id | name
1  | Audi
2  | Ferrari
3  | BMW

Person Car Table

id | person_id | car_id | color
1  | 1         | 1      | "Red"
2  | 1         | 2      | "White"
3  | 1         | 3      | "Black"
4  | 2         | 1      | "Pink"
5  | 2         | 3      | "Yellow"
6  | 3         | 2      | "Black"

Person class

public function cars()
{
        return $this->hasMany(Car::class);
}

Kindly help write a query where I want to find out who is the owner of the exact specified cars.

For eg

car_id = 2 then person_id = 3
car_id = 1,2,3 then person_id = 1
car_id = 1,3 then person_id = 2
car_id = 1,2 the person_id = null

I have comeup with the following query but it is not working:

Person::whereHas('cars', function($q) use($cars) {
         foreach($cars as $car) {
              $q->where('car_id', $car);
        }
    })
    ->first()
0 likes
1 reply
willvincent's avatar

Do you have the other side of the relationship defined? In the car class:

public function owner() {
  return $this->belongsTo(Person::class);
}

Is there any reason you can't come at it from the other direction?

// Get cars, with their owner:
$cars = Car::with('owner')->get();
1 like

Please or to participate in this conversation.