Adding default role on registration with Entrust a

2019-08-25 03:12发布

问题:

I'm trying to learn Laravel and I'm checking some ACL's along the way. Currently I'm testing Entrust/Zizaco and I'm trying to add default role when user is registered.

I've added this to the create function in RegisterController.php

$user = User::find($create->id);
$role = Role::where('name', '=', 'customers')->firstOrFail();
$user->roles()->attachRole($role->id);

This is full function

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

    $user = User::find($create->id);
    $role = Role::where('name', '=', 'customers')->firstOrFail();
    $user->roles()->attachRole($role->id);
    return $user;
}

The problem is that the user is created but the role isn't assigned. No errors also. Can anyone help me a bit here?

回答1:

You should attach the roles directly to the user, so:

$user->roles()->attachRole($role->id);

Should be

$user->attachRole($role); OR $user->roles()->attach($role->id);

You can read more about it and find examples on: https://github.com/Zizaco/entrust#concepts

UPDATE

In your create function, you return the created users directly, so the function stops there. Change it, so you assign the created user, and return it later, after the role attaches.

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

    $role = Role::where('name', '=', 'customers')->firstOrFail();
    $user->attachRole($role);

    return $user;
}


标签: php laravel-5