Use withCount():
$flights = Flight::withCount('tourists')
->having('seats', '>', DB::raw('tourists_count'))
->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Here's my simplified 'flights' table: id seats
and pivot table (used for bookings) flight_id tourist_id
Now in the controller I got: $flights = Flight::all();
My question is, how do I get only those flights that have free seats available for booking and pass those flights to view? I would need to get flight_id count from pivot for each flight and if it's less than $flight->seats than keep it and than pass it on.
Any thoughts?
Use withCount():
$flights = Flight::withCount('tourists')
->having('seats', '>', DB::raw('tourists_count'))
->get();
Please or to participate in this conversation.