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

joha's avatar
Level 1

Query ManyToMany relations

Have a good day... Cars and Owners are connected with Pivot table relation belongsToMany

How to  filter Cars by Owners  age where age is 25?

table cars = id, message..., timestamp; table owners = id, name, role ... timestamp; table car_owner = id, car_id, owner_id;

I need to show All Cars that Owners with the age 25 used

I had another filters also , this is code below

table-> cars;
public function owners()
 {
        return $this->belongsToMany('App\Models\Owner');
 }

table-> owners;

public function cars()
 {
       return $this->belongsToMany('App\Models\Cars');
 }

in Controller:


$cars = Cars::when($selected_city_exist, function ($query, $selected_city)  {
                    return $query->where('city', (int)$selected_city);
        })
          .....
        ->when($type_exist, function ($query,  $type) {
            return $query->where('type', (int)$type);
        })->paginate(50);

So I dont know How to check owners also inside this query

0 likes
1 reply
Nakov's avatar
Nakov
Best Answer
Level 73

@joha you can use ->whereHas to filter them out: https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence

$cars = Cars::when($selected_city_exist, function ($query, $selected_city)  {
    return $query->where('city', (int)$selected_city);
})
->whereHas('owners', function($query) {
    $query->where('birthday', '<=', now()->subYears(25));
})
->when($type_exist, function ($query,  $type) {
     return $query->where('type', (int)$type);
})->paginate(50);	

Please or to participate in this conversation.