I would personally prefer the single pivot table way since it would be faster to query and easier to access.
Laravel provides an easy way to access custom pivot attributes, so you can put your role there, for example as a string access_level or something like that. If you would like to introduce custom role models to furthermore complicate your logic, then you can use a custom pivot model and bind a relationship method to it. If you need some examples, I can provide some, but you can find all you need in the laravel documentation here: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many
User Relationships
What would be the best way to construct my database tables to allow for the following relationships.
- A project has an owner
- A project has many collaborators
- A collaborator can have different permission levels per project
Using Eloquent I would like to be able to show a single list of projects per user, for example:
USER A
- Project 1 (Owner)
- Project 2 (Owner)
- Project 3 (Collaborator - Editor)
- Project 4 (Collaborator - Read only)
Some questions:
- If I add a 'user_id' column in the projects table and a pivot table for 'many-to-many' relationships between users and projects will I easily be able to use an Eloquent query to display a single list of projects? I.e. because I will need to check both the user_id column in the projects table and the pivot table.
- Would it be better to use a single pivot table and assign a permission level as part of the pivot table, so on a relationship by relationship basis I could define the link between the user and the project and then somehow also add a permission type method?
I am new to Laravel, and just seeking clarification/advice on best practices for this kind of thing.
Thanks
Yes, your migrations seem just about right. I can only share a couple of notes from my experience:
-
a tricky problem you might encounter depending on your database engine: initially the foreign keys and the primary keys must be of the exact same type and length for the foreign key constraints to work and not throw an error. So you'll want the ids on your users and projects table to also be
unsignedIntegers. -
Another thing you might want to consider is the default naming convention of the pivot tables:
project_user, which can spare you a couple of table name specifications. -
in order to use a custom pivot model, as far as I recall, you need to give the pivot records an
idcolumn, so that eloquent can treat them as a model
Then all you'll need in your User model would be a method like the following:
public function projects()
{
return $this->belongsToMany(App\Project::class)->withPivot('id', 'role_id')->using(App\ProjectUser::class);
}
For more details on the custom pivots, refer to the documentation: https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models
Cheers and happy coding! ^^
Please or to participate in this conversation.