Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

User Role Pivot Table Structure and Model

After watching the users and roles lesson on laracasts I developed my own with the same tables names however the different between the lesson and my user_roles pivot table is that a user can only be assigned to one role at a time. They can only be a user or an admin or an editor.

Is there anything wrong with this?

I ask this because when I get to permissions I would like to assign permissions to a role and maybe eventually be able to modify a user's permissions that say is a admin but I want to add or remove a specific permission that others of the same role can or can not do.

If this is an okay database table structure for the pivot table to only allow a user to have a single role then would I use the hasOne() for the relationship. Or how would I handle the relationship inside the models or what would I do with the three models I have: User, Role, UserRoleAssigned?

0 likes
11 replies
bashy's avatar

Depends what relation you have set. A pivot will provide you with the ability to add multiple user_id to a role_id if the structure is like this

id user_id role_id

Then like this for the data

id | user_id | role_id

1 - 1 - 1

2 - 1 - 2

jrdavidson's avatar

That's exactly how I have it set up bashy. How would each of the role and user model look then.

bashy's avatar

User model

public function roles()
{
    return $this->belongsToMany('Role');
}

Role model (for finding all users with a certain role)

public function users()
{
    return $this->belongsTo('User');
}
jrdavidson's avatar

So those relationships in the models have nothing to do with the pivot table? Or am I mistaken?

bashy's avatar

They do. Eloquent will use it and join the tables from the pivot table.

lkmadushan's avatar

You don't need a pivot table for one to one relationship. It is necessary if you have many to many relationships.

User Model

public function role()
{
    return $this->hasOne('Role');
}

Role Model

public function user()
{
    return $this->belongsTo('User');
}

jrdavidson's avatar

That's what I thought I didn't know if it was important to do them in a pivot table. Should I just make a field in the users table for role_id?

lkmadushan's avatar

yes. you have to add a filed as role_id in user table.

jrdavidson's avatar

So that relationship would be for user model of hasOne or belongsTo role? And then role model would be hasMany?

bashy's avatar
bashy
Best Answer
Level 65

hasOne('Role') means it would look for a role_id field in the table

belongsTo('User') is the opposite so it looks for all IDs of that ID in the users table

Best to just try it and read the errors.

1 like

Please or to participate in this conversation.