在Entrust和Laravel 5.6上注册时添加默认角色 [英] Adding default role on registration with Entrust and Laravel 5.6

查看:76
本文介绍了在Entrust和Laravel 5.6上注册时添加默认角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Laravel,并且正在检查一些ACL.目前,我正在测试Entrust/Zizaco,并且尝试在注册用户时添加默认角色.

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.

我已将其添加到RegisterController.php

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

这是全部功能

/**
 * 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?

推荐答案

您应该将角色直接附加到用户,所以:

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

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

应该是

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

您可以阅读有关它的更多信息并在以下位置找到示例: https://github.com/Zizaco/entrust#concepts

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

更新

在您的create函数中,您直接返回创建的用户,因此函数在此处停止.进行更改,以便您分配创建的用户,并在角色附加后再返回.

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;
}

这篇关于在Entrust和Laravel 5.6上注册时添加默认角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆