Here's what I was doing before the error occurred
I'm trying to assign a role for a user from my users
and roles
table in a new table called `role_users'.
Role.php model
class Role extends Model{
public function users(){
return $this->belongsToMany('App\User','role_users', 'role_id', 'user_id');
}
}
User.php model
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function roles(){
return $this->belongsToMany('App\Role', 'role_users', 'user_id', 'role_id');
}
}
I keep getting the error in this line from my AccountController.php
$roleuser = new User;
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/
I'm having Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into 'role_users' ('role_id', 'user_id') values (1, ))
. The users table
is already updated and the user_id
has already been saved to the database.
Can someone help me? I must have overlooked some important stuff.
The problem here is that you don't attach role to any existing user, you just run:
$roleuser = new User;
to create user object that is not save to database.
You should rather do something like this:
$roleuser = User::find(1); // find user with id 1
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/
or
$roleuser = User::create(['name' => 'Sample user']); // create sample user
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/
You should also don't use $roleuser
variable here, because it's obviously $user