Laravel-permission: Integrity constraint violation: 1048 Column 'model_id' cannot be null

Created on 11 Sep 2018  路  13Comments  路  Source: spatie/laravel-permission

my package details are
"laravel/framework": "5.6.*",
"spatie/laravel-permission": "^2.19"

when i assign a role
$user->syncRoles(['role']);
$user->assignRole('role');

IlluminateDatabaseQueryException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'model_id' cannot be null (SQL: insert into model_has_roles (model_id, model_type, role_id) values (, AppUser, 2))

thanks in advance

support

Most helpful comment

You can't sync something to a model that hasn't been persisted yet.

You must call $user->save() before you sync or assign.

All 13 comments

In your Eloquent model for App\User, what is the column-type for your id field?

This package expects it to match the model_id type of the model_has_roles table.

id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
how I match model_id?

What is the value for model_morph_key in your config/permission.php?

https://github.com/spatie/laravel-permission/blob/master/config/permission.php#L83

the value is
'model_morph_key' => 'model_id',
do i need to change it to "id"? right?

No, it should be model_id.

This is puzzling. I think you've changed something in your App\User model that's causing it.
It's hard to troubleshoot this without seeing your code.

below is the my user model`

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
use SpatiePermissionTraitsHasRoles;

class User extends Authenticatable
{
use Notifiable, HasRoles;

/**

  • The attributes that are mass assignable.
    *
  • @var array
    */
    protected $fillable = [
    'name', 'email', 'password',
    ];

/**

  • The attributes that should be hidden for arrays.
    *
  • @var array
    */
    protected $hidden = [
    'password', 'remember_token',
    ];

}
`

Can you share the code where you're trying to assign and sync roles to users?

$user = new \App\User(); $user->name = 'dev'; $user->email = ''; $user->password = bcrypt(''); $user->syncRoles(['role']); $user->assignRole('role'); $user->save();

its in seeds
this is how i create roles in seed
$role = Role::create(['name' => 'admin']);

You can't sync something to a model that hasn't been persisted yet.

You must call $user->save() before you sync or assign.

@drbyte thank you it works. but it should send a proper message. thank you anyway

Thank you @drbyte you saved my day.
You are my hero :D

Hello,
I have a similar problem, but $user->save(); didn't fix the problem for me.
Can I describe it here or need to create a new issue?

@brenoassp Please open a new issue for it, containing as much information as possible to recreate your problem with a fresh Laravel install.

Was this page helpful?
0 / 5 - 0 ratings