Integrity constraint violation: 1048 Column 'user_id' cannot be null error occurs when assigning roles (Laravel 5.3)

时光毁灭记忆、已成空白 提交于 2019-12-11 02:05:40

问题


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.


回答1:


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




回答2:


You can't attach relation to non existing user. Try to create user first:

$roleuser = User::create(['name' => 'John']); // Instead of new User;

Or fetch user from DB:

$roleuser = User:find(1);


来源:https://stackoverflow.com/questions/41245657/integrity-constraint-violation-1048-column-user-id-cannot-be-null-error-occur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!