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

tnort's avatar
Level 4

Query builder (one-to-many and many-to-many)

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

0 likes
5 replies
tnort's avatar
Level 4

@MichalOravec,

Thank you for the replay, but I still cannot figure out how to put it all in a single query :(.

I have received in the backend an university_id and city_id but I am not able to build a single query using the two of them.

tnort's avatar
Level 4

I've tried something like that but doesn't seem to work

Course::where('university_id', 1)->whereHas('cities', function (Builder $query){$query->where('city_id',1);})->get()

MichalOravec's avatar
Level 75

@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.