Skip to content
Advertisement

Laravel 6 many to many relationship

In laravel 6, I have 2 models

I have third model to join tables

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

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:

An the student model:

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