Search code examples
phplaravelentrust

Laravel 5.2, Entrust, 'role_user' table not updating


So I'm working with Laravel 5.2 and Entrust package to manage roles/permissions

I'm building a function which should add a user to the 'users' table simultaneously add a relationship to the 'role_user' table. I'm passing an array from a multi_select and then attaching that to a user.

It adds the user to the 'users' table perfectly, but does not add the relationship in the 'role_user' table. I would love some help figuring out what is wrong.

The part of the form in question:

{!! Form::select('roles[]', $roles, null, ['multiple' => 'multiple', 'class' => 'select-width-100 form-control roles']) !!}

My StoreUser function

public function StoreUser(Request $request)
{

    $input = Request::all();
    $user = New User;
    $user->name = $input['username'];
    $user->email = $input['email'];
    $user->password = Hash::make($input['password']);

    $roles = $input['roles'];
    foreach ($roles as $role)
    {
        $role_id = Role::where('name', $role)->first();
        $user->roles()->attach($role_id);
    }
    $user->save();
    return redirect('/settings/users');

}

Below is my User.php Model

<?php

namespace App;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{

    use EntrustUserTrait;

    /**
     * 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',
    ];
}

Solution

  • I Managed to fix it. I should be looking for 'id' instead of 'name', so this:

    foreach ($roles as $role)
    {
        $role_id = Role::where('name', $role)->first();
        $user->roles()->attach($role_id);
    }
    

    Should be this:

    foreach ($roles as $role)
            {
                $role_id = Role::where('id', $role)->first();
                $user->roles()->attach($role_id);
            }