Skip to content
Advertisement

Laravel 6 many to many relationship

In laravel 6, I have 2 models

class Teacher {

}

class Students {

}

I have third model to join tables

class TeacherStudent {

}

Now how can I get all the teachers those are not subscribed by a particular student?

For example:
Teacher1, Teacher2, Teacher3, Teacher4 are in the Teacher table
and Student1, Student2, Student3, Student4 are in the Student table

Student1 subscribed Teacher1, Teacher2
Student2 subscribed Teacher1, Teacher4
Student3 subscribed Teacher2

Here, as logedin as Student1 when I want to see unsubscribed teachers, I should get Teacher3 and Teacher4
as logedin as Student4 when I want to see unsubscribed teachers, I should get all teachers and so on

Advertisement

Answer

I’m assuming you’ve defined all relations in your models

// in your controller
$user = auth()->user();

// where 'students' is a many-to-many relationship you have in you Teacher model
$teachers = Teacher::whereDoesntHave('students', function($query) use($user) {
    return  $query
          ->where('user_id', $user->id);
});

The above query will retrieve all teachers that don’t belong to current authenticated user.

In case you haven’t defined any relation in your models. They should look something like this:

// Teacher model
public function students() {
  // many to many relationship
  return $this->belongsToMany('AppStudent', 'subscriber'); // replace subscribers with your pivot table
}

An the student model:

// Student model
public function teachers() {
   // many to many relationship
   return $this->belongsToMany('AppTeacher', 'subscriber'); // replace subscribers with your pivot table
}

PS: haven’t tested any of that, let me know if they don’t work

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement