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

Gianni3g's avatar

how can i assing one or many roles to a user at the sign up

Hello, I'm new with Laravel. I'm trying to add one or many roles to user at the sign up.

I did the authentification with artisan make:auth, then I made the models and the relations.

When i register a user, the new user is well created but his role is not assigned, i've tried to retrieve a user and assign a role to it with tinker and it works. But at the register the role is not assigned. How can I fix that and how can I assign different roles with checkboxes?

Here are my registrationController and a part of my form.

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'role' => $data['role']
        ]);

        dd($roleValue = $user->role);
`
        if($roleValue == 'senior')

        $userRole = Role::Where('name','senior')->first();

        

        if($roleValue == 'prestataire')

            $userRole = Role::Where('name','presta')->first();

        

        $user->roles()->attach($userRole);

        return $user;
    }
}

the dd($roleValue = $user->role); returns null...

                        <input type="checkbox" id ="role" name="role" value="senior">Je m'inscris en tant que sénior, je recherche un servive<br>
                        <input type="checkbox" id ="role" name="role" value="prestataire" checked> Je m'inscris en tant que prestataire,je propose mes services<br>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>

0 likes
3 replies
sureshamk's avatar

Check your user model and its role method for correct relationship. You can share your user model code it will help me to assist you.

Tip:

While attaching actually you are need pass array of role ids . So you have to modify your html checkbox

<input type="checkbox" id ="role" name="role[]" value="{{--Place Your role-id}}">Je m'inscris en tant que sénior, je recherche un servive<br>
                        <input type="checkbox" id ="role" name="role[]" value="{{--Place Your role-id}}" checked> Je m'inscris en tant que prestataire,je propose mes services<br>

1 like
Gianni3g's avatar

Thank you.

<?php

namespace App;

use App\Permissions\HasPermissionsTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, HasPermissionsTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function annonces()
    {

        return $this->hasMany(Annonce::class);
    }
}

This the trait

<?php

namespace App\Permissions;

use App\{Role, Permission};


trait HasPermissionsTrait
{

    public function hasRole(... $roles)
    {
        foreach($roles as $role){

            if($this->roles->contains('name', $role)){

                return true;
            }
        }

        return false;
    }

    public function givePermissionTo(... $permissions)
    {

        
        $permissions = $this->getPermissions(array_flatten($permissions));

        if ($permissions === null) {

            return $this;
        }

        $this->permissions()->saveMany($permissions);

        return $this;
    }

    public function revokePermissionTo(... $permissions)
    {

        $permissions = $this->getPermissions(array_flatten($permissions));

        $this->permissions()->detach($permissions);

        return $this;
    }

    public function updatePermissions(...$permissions)
    {
        //detach all
        $this->permissions()->detach();

        return $this->givePermissionTo($permissions);
        

        
    }

    protected function getPermissions(array $permissions)
    {

        return Permission::WhereIn('name', $permissions)->get();
    }
    public function hasPermissionTo($permission)
    {
        return $this->hasPermissionRole($permission) || $this->hasPermission($permission);
    }

        //vérifie si un rôle à la permission de faire une action
    protected function hasPermissionRole($permission)
    {
        foreach($permission->roles as $role){

            if($this->roles->contains($role)){

                return true;
            }
        }

        return false;
    }

    protected function hasPermission($permission)
    {

        return (bool) $this->permissions->where('name', $permission->name)->count();
    }




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

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'users_permissions');
    }
}
<?php

namespace App\Permissions;

use App\{Role, Permission};


trait HasPermissionsTrait
{

    public function hasRole(... $roles)
    {
        foreach($roles as $role){

            if($this->roles->contains('name', $role)){

                return true;
            }
        }

        return false;
    }

    public function givePermissionTo(... $permissions)
    {

        
        $permissions = $this->getPermissions(array_flatten($permissions));

        if ($permissions === null) {

            return $this;
        }

        $this->permissions()->saveMany($permissions);

        return $this;
    }

    public function revokePermissionTo(... $permissions)
    {

        $permissions = $this->getPermissions(array_flatten($permissions));

        $this->permissions()->detach($permissions);

        return $this;
    }

    public function updatePermissions(...$permissions)
    {
        //detach all
        $this->permissions()->detach();

        return $this->givePermissionTo($permissions);
        

        
    }

    protected function getPermissions(array $permissions)
    {

        return Permission::WhereIn('name', $permissions)->get();
    }
    public function hasPermissionTo($permission)
    {
        return $this->hasPermissionRole($permission) || $this->hasPermission($permission);
    }

        //vérifie si un rôle à la permission de faire une action
    protected function hasPermissionRole($permission)
    {
        foreach($permission->roles as $role){

            if($this->roles->contains($role)){

                return true;
            }
        }

        return false;
    }

    protected function hasPermission($permission)
    {

        return (bool) $this->permissions->where('name', $permission->name)->count();
    }




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

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'users_permissions');
    }
}<?php

namespace App\Permissions;

use App\{Role, Permission};


trait HasPermissionsTrait
{

    public function hasRole(... $roles)
    {
        foreach($roles as $role){

            if($this->roles->contains('name', $role)){

                return true;
            }
        }

        return false;
    }

    



    protected function hasPermission($permission)
    {

        return (bool) $this->permissions->where('name', $permission->name)->count();
    }




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

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'users_permissions');
    }
}<?php

namespace App\Permissions;

use App\{Role, Permission};


trait HasPermissionsTrait
{

    public function hasRole(... $roles)
    {
        foreach($roles as $role){

            if($this->roles->contains('name', $role)){

                return true;
            }
        }

        return false;
    }

    





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


}

and this is the role model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'roles_permissions');
    }
}
Gianni3g's avatar

sorry i wrote the trait twice. This the haspermissionstrait actually

<?php

namespace App\Permissions;

use App\{Role, Permission};


trait HasPermissionsTrait
{

    public function hasRole(... $roles)
    {
        foreach($roles as $role){

            if($this->roles->contains('name', $role)){

                return true;
            }
        }

        return false;
    }

    public function givePermissionTo(... $permissions)
    {

        
        $permissions = $this->getPermissions(array_flatten($permissions));

        if ($permissions === null) {

            return $this;
        }

        $this->permissions()->saveMany($permissions);

        return $this;
    }

    public function revokePermissionTo(... $permissions)
    {

        $permissions = $this->getPermissions(array_flatten($permissions));

        $this->permissions()->detach($permissions);

        return $this;
    }

    public function updatePermissions(...$permissions)
    {
        //detach all
        $this->permissions()->detach();

        return $this->givePermissionTo($permissions);
        

        
    }

    protected function getPermissions(array $permissions)
    {

        return Permission::WhereIn('name', $permissions)->get();
    }
    public function hasPermissionTo($permission)
    {
        return $this->hasPermissionRole($permission) || $this->hasPermission($permission);
    }

        //vérifie si un rôle à la permission de faire une action
    protected function hasPermissionRole($permission)
    {
        foreach($permission->roles as $role){

            if($this->roles->contains($role)){

                return true;
            }
        }

        return false;
    }

    protected function hasPermission($permission)
    {

        return (bool) $this->permissions->where('name', $permission->name)->count();
    }




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

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'users_permissions');
    }
}

All the methods about the permissions are not important i don't use them for now

Please or to participate in this conversation.