Laravel-permission: Field model_type doesn't have a default value

Created on 10 Oct 2017  路  4Comments  路  Source: spatie/laravel-permission

I am trying to assign role to a user when seeding the database
$user->assignRole('master');
But I'v got this error
Field 'model_type' doesn't have a default value

Is there any thing I'v missed?

Most helpful comment

I found the problem, its because I have this function in my User model.

public function roles(){
        return $this->belongsToMany(Role::class,'role_users','user_id','role_id');
    }

I thought that the trait HasRoles will take care of this relation. So I removed it and it worked fin. But still the model_id stored as 0

All 4 comments

Hi, I can't seem to replicate this issue. The model_type field should be automatically filled in by Laravel's morphToMany relationship.

Are you by any chance using morph maps or any other packages that might influence this? What version of the Laravel and the package are you using?

I am using laravel 5.5 without any extra packages other that "laravel-permission".
I only changes these lines in migrations:

$table->morphs('user');
$table->primary(['permission_id', 'user_id', 'user_type']);

And I did not use morphToMany. But I used my own Role and Permission model and make it extends Spatie models. Is there any thing I should take care of when do that?

Another thing to mention is that I tried to set App\User as a default value from mysql, But when I call $user->assignRole('master'); the user_id in the inserted row of role_users is 0

I found the problem, its because I have this function in my User model.

public function roles(){
        return $this->belongsToMany(Role::class,'role_users','user_id','role_id');
    }

I thought that the trait HasRoles will take care of this relation. So I removed it and it worked fin. But still the model_id stored as 0

The zero problem was solved by public $incrementing = false; for User model.
I think all these problems are made by me 馃

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wreighsantos picture wreighsantos  路  4Comments

devingray picture devingray  路  3Comments

dylangeorgeharbour picture dylangeorgeharbour  路  3Comments

bbdangar picture bbdangar  路  4Comments

bhulsman picture bhulsman  路  3Comments