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

jbowman99's avatar

Adding roles to a user

So this one has been getting me for the past few days, without bringing in an outside package. How can I assign roles to a user upon creating "them".

I have a registration form, roles table, users table and a role_user table all of the current users will be hard coded with roles upon release but as a new user is being created how can i add a field to assign them this role?

I have these functions in my User model, just not sure how to implement the assignRole function

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

public function hasRole($name)
{
    foreach ($this->roles as $role)
    {
        if($role->name == $name) return true;
    }
    return false;
}

public function assignRole($role)
{
    $this->roles()->attach($role);
}
0 likes
14 replies
davorminchorov's avatar

I assume you have a form with fields like username, first name, last name, password etc and a role select box. Each role should have the id of that role as the value.

//find the role by id
$role = Role::findOrFail($request->role_id) // select name="role_id" 
// $request->role_id or $request->get('role_id') is the same thing.
// create the user
$user = User::create($request->all());
// assign the role to a user based on the select box from the form.
$user->assignRole($role);
// return a view

jbowman99's avatar

User Creation:

protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'username' => $data['username'], 'password' => bcrypt($data['password']), ]); }

yes i have the form username, password etc. I do not have a role select box as of now

kfirba's avatar

@jbowman99 Hey there. First I have to give you an advice as of how to fix your hasRole() method. You can just replace that foreach loop with a single like of code:

public function hasRole($name)
{
    return in_array($name, $this->roles);
}

Now as for your question, you can simply listen to the event of a user created in a service provider:

public function boot()
{
    User::created(function($user) {
        $user->assignRole($role);
    });
}
Prullenbak's avatar

If you're using the default Laravel 5.1 auth stuff, and you want to assign a default role to every new user, you could edit the create method in App\Http\Controllers\Auth\AuthController.php


    protected function create(array $data)
    {
       $user =  User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

    //create role entry here
    
    return $user;
    }
jbowman99's avatar

Still trying to wrap my head around this. in the form it will be a selection box:

user admin clerk

in the user model?

jbowman99's avatar

assignRole($name) <- which is the name they select from the selection box

attachRole to the user.....

davorminchorov's avatar
Level 53

To fill up the select with roles you have to pass a variable to the view like:

$roles = Role::lists('role', 'id')->all();
return view('users.create', compact('roles'));

now in your view you have to do something like:

<select name='role_id'>
    <option value="" selected="selected">Select A Role</option> 
    @foreach($roles as $id => $role)
        <option value="{!! $id !!}">{!! $role->role !!}</option>
    @endforeach
</select>
jbowman99's avatar

Trying to get property of non-object

somwhere in here:

@foreach($roles as $id => $role) {!! $role->role !!}

jbowman99's avatar

seems to be dd'ing the correct information now, when it comes to attaching this info to the user

public function store() { if (Auth::attempt(Input::only('username', 'password'))) { "would i put it here" -> $user->roles()->attach($request->input('roles)); return Auth::user(); } return 'Failed!'; }

Please or to participate in this conversation.