dourong6054 2015-06-16 15:17
浏览 176
已采纳

无法将值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.

  • 写回答

1条回答 默认 最新

  • douzhaishan5462 2015-06-16 15:26
    关注

    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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3