StackOverflowed
StackOverflowed

Reputation: 5975

Finding User object where object in hasMany relationship

I have a User object, and in that user I define the following relationship:

public function car()
{
   return $this->hasMany('Car');
}

Now if I want to find a User with a Ford, how can I accomplish something like this?

$user = User::where('car.make', 'ford')->first();

Thanks

Upvotes: 0

Views: 30

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219920

Use whereHas:

$user = User::whereHas('car', function($query) {
    $query->where('make', 'ford');
})->first();

BTW, since this is a has-many relationship, you should probably rename the relationship to cars.

Upvotes: 2

Related Questions