Use whereHas for that
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I have a one to one relationship (course->university) and a many to many relationships (course -> cities) I am trying to query all courses that belong to a specific university and are held in a specific city.
I can get all courses that are linked to a specific (Course::where('university_id', university_id)->get()) but I cannot figure out how to also pull/filter down the courses to the specific city.
Thank you, Mihail
@tudosm Learn how to write code here on Laracasts...
$courses = Course::where('university_id', 1)->whereHas('cities', function ($query) {
$query->where('id', 1);
})->get();
Please or to participate in this conversation.