-1

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.

xhulio
  • 1,093
  • 1
  • 13
  • 32
  • This may sound silly, but is your User table column `user_id` configured to auto increment? – visevo Jun 16 '15 at 15:20
  • yes it is. the problem is in the pivot table, somehow the `id` doesn't pass to the `user_id` column of the pivot table. – xhulio Jun 16 '15 at 15:22
  • Looking at `$user->create($request->all());` have you verified that the user is being created? Try `print_r($user)`. – visevo Jun 16 '15 at 15:26
  • i checked in the database, the user is created – xhulio Jun 16 '15 at 15:27

1 Answers1

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');
}
xhulio
  • 1,093
  • 1
  • 13
  • 32
Jirennor
  • 1,279
  • 1
  • 9
  • 14