无法将值NULL插入列'user_id',表'dbo.role_user'; 列不允许空值

I am using Zizaco/Entrust in Laravel 5.0 to apply RBAC and i'm having the following error:

Cannot insert the value NULL into column 'user_id', table 'dbo.role_user'; column does not allow nulls. INSERT fails. (SQL: insert into [role_user] ([role_id], [user_id]) values (2, ))

I followed all the steps to implement Entrust and at my User.php store method i have:

public function store(UserRequest $request)
{
    $user = new User();
    $user->create($request->all());
    $roles=$request->get('role_id');
    $user->roles->attach($roles);
    return redirect('users');
}

I want to know how can I fix this issue. All the help is appreciated.

duanlong4890
duanlong4890 我在数据库中检查了用户是否已创建
大约 5 年之前 回复
dougu3591
dougu3591 查看$user->create($request->all());你验证过用户是否正在创建?试试print_r($user)。
大约 5 年之前 回复
duandao1931
duandao1931 是的。问题出在数据透视表中,不知何故,id没有传递给数据透视表的user_id列。
大约 5 年之前 回复
douyu7618
douyu7618 这可能听起来很愚蠢,但是你的用户表列user_id是否配置为自动递增?
大约 5 年之前 回复

1个回答

Extra info: Entrust needs a userid to be able to assign a role to the user. When you create a user there is no userid cause a userid will be created when you create the user. So after creating the user you need to retrive the user first before you can assign it to a role.

Here: See the second code block from this URL: Entrust Github. They receive the user first and then assign it to a role.

First create the user like this:

User::create($request->all());

Then grab the newly created user like this:

$User = User::where('username', '=', $request->username)->first();

Then assign the user to the role like this:

$User->roles()->attach($request->roleid);//parenthesis missing

All together:

public function store(UserRequest $request)
{
    User::create($request->all());

    $User = User::where('username', '=', $request->username)->first();

    $User->roles()->attach($request->roleid);

    return redirect('users');
}
dty97501
dty97501 编辑Xhulio的Thx,我错过了()部分。
大约 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问