Search code examples
phplaravelcrudrolesuser-management

Laravel adding a role to a newly created user


I am creating a new user from my already made CRUD, however, I don't know how I can also assign a role to the user we are creating. I am working with Laravel and 3 tables. I have 1 table that is my users table, 1 table that is my roles table, and 1 table that is my bridge table between roles and users. I have this made because my users can have more than 1 role assigned to themselves.

My question now is how do I give the user a role and how do I save the user to all the tables I mentioned before. Please remember I am working from a crud, so I have a create view.

Greetings and thanks for all the help!


Solution

  • Assuming you have these tables:

    • users
    • roles
    • role_user

    Where role_user has a role_id and a user_id column. Then your models would look something like:

    class User extends Model
    {
    
        /**
         * Roles relationship.
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
         */
        public function roles(): BelongsToMany
        {
            return $this->belongsToMany(Role::class);
        }
    }
    
    class Role extends Model
    {
    
        /**
         * Users relationship.
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
         */
        public function users(): BelongsToMany
        {
            return $this->belongsToMany(User::class);
        }
    }
    

    And because it's a BelongsToMany relation, you would use the sync or syncWithoutDetaching methods to add or synchronise user roles. Or attach() for adding a single role to a user. For example:

    // The $role variable can be a model instance, or an ID of the role.
    $role = Role::all()->random();
    $user = User::all()->random();
    
    $user->roles()->syncWithoutDetaching($role);
    
    // or
    $user->roles()->attach($role);
    

    I would recommend looking at the documentation for managing the relations (link). Because sync for example removes relations that aren't provided in the given array of models or ID's to synchronise - which would result in an unexpected behaviour if you aren't aware of this behaviour.