Three Way Eloquent Relationship

- 1 answer

The project that I am working on requires a sort of sharing functionality meaning that when a person creates an exercise they can choose to share that exercise with another person and append a certain permission to that exercise (i.e read, write, or execute).

I have three tables(all of which have models): users, exercises, and permissions. In the middle I have an exercise_permission_user table that only has three columns: exercise_id, permission_id, and user_id all of which are foreign keys that point back to their respective tables.

The problem comes with establishing a three way many to many relationship among these tables in Laravel 5. More specifically, when a person shares an exercise, I need to input the id's of the exercise being shared, the user it is being shared with, and the permission that is being appended into the exercise_permission_user table. I then need to be able to query the user_id of this table and see all exercises that are being shared with a certain user. If the user Mike has an ID of 3, then I would like to query the middle table for that ID and find the exercise he has access to as well as the permission that he is being granted.

I am still in the learning process when it comes to eloquent so any help would be greatly appreciated. I am not necessarily looking for someone to build this for me, just some help that will give me the information necessary to do it on my own. Thanks to all that help!



I've struggled with this issue a couple of times. As far as I could research, I didn't find a Laravel native way of coding this kind of three way many to many relationship. What I generally do is to create a model for the pivot table. So, a SharedExercise model (or the name you want to use) with a protected $table property set as 'exercises_permission_user'. Inside that model you set the relationships with user, exercises and permissions. Then, you can write:

$sharedExercises = SharedExercise::where('user_id', $userId)->get();

Pay attention to the table and model naming. I usually name tables using laravel's conventions, but when I have this 3 way many to many, I try to find a more describing name than the convention. So, for example instead of exercises_permission_user and ExercisePermissionUser model, maybe shared_exercises and SharedExercise names are better. Note that this isn't THE way to do it. It's how I do it as a result of not finding a convention in the documentation.