Laravel Eloquent Many-to-Many query

Viewed 69

I have many to many relationship between two tables for e.g. lecture and students (users).

Now if the lecture is private or limited to invited users only than lecture_student table has entries in it with student_id.

lecture_student has student_id and 'lecture_id' keys.

So if lecture is limited to some students then lecture_student will have list of all user_id rows in it else it is open for all.

When a user logs in I display list of Lectures using following query

Lecture::where('user_id', '<>',$logged_in_user->id)
    ->futureLectures() // query scope defined for future lectures only
    ->get()

How do I get the lecture for a student where he/she is invited to and also open for all?

Above query gets me all the lectures weather student is invited to that lecture or not.

I tried whereHas but it does not work because lecture_student table only has entry in case the lecture is limited to some users, in case of open lecture, lecture_student has not row.

Thank you

1 Answers

You can Query Relationship Existence to get the lectures where logged student was invited

whereHas('students', function ($query) use ($logged_in_user) {
    $query->where('id', $logged_in_user->id);
})

and Query Relationship Absence with orDoesntHave, to get too the lectures that has no related (invited) students.

orDoesntHave('students')

Do that inside a Parameter Group.

Lecture::where(function ($query) use ($logged_in_user) {
        $query->whereHas('students', function ($q) use ($logged_in_user) {
                $q->where('id', $logged_in_user->id);
            })
            ->orDoesntHave('students');
    })
    ->futureLectures()
    ->get();
Related