Laravel-permission: Role::create without "name" filled throws Undefined index "name"

Created on 24 Jan 2020  路  6Comments  路  Source: spatie/laravel-permission

Role::create() throws exception Undefined index "name" when trying to save Inherited Role model without name filled but with Observer that generates name on creating event:
Model:

namespace App;

use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    public $guard_name = 'admin';

    protected $fillable = ['title'];
}

Observer:

namespace App\Observers;

use App\Role;
use Illuminate\Support\Str;

class RoleObserver
{
    public function creating(Role $role)
    {
        $role->name = Str::slug($role->title, '-');
    }
}
question support

All 6 comments

If you are extending or replacing the role/permission models, you will need to specify your new models in this package鈥檚 config/permissions.php file.

First be sure that you鈥檝e published the configuration file (see the Installation instructions), and edit it to update the models.role and models.permission values to point to your new models.

Note the following requirements when extending/replacing the models:

Extending
If you need to EXTEND the existing Role or Permission models note that:

Your Role model needs to extend the Spatie\Permission\Models\Role model
Your Permission model needs to extend the Spatie\Permission\Models\Permission model

Thanks, I forgot to set proper models in config, my bad.

Okay, exception still appears even with my models defined in config. (config cache disabled)

return [
    'models' => [
        'permission' => App\Permission::class,
        'role' => App\Role::class,
    ],

I think problem in overloaded method create without eloquent event triggers. name attribute checks before observer calls.

@Briareos17 what's the complete error message?
And what's the complete code for your overloaded method?

Complete code in package:
Spatie\Permission\Models\Role
Spatie\Permission\Models\Permission

This methods prevent triggering observer creating/updating/saving methods beign called before name attribute check at Spatie\Permission\Models\Permission:37 and Spatie\Permission\Models\Role:36

The behavior is by design, particularly since it's intentionally doing a lookup so it can throw an exception in the case of duplicates.

But, since you're extending the model to do other things already, you're welcome to override the create() method in your model. Or, you could also explore making the name field nullable in the db and passing name as null when calling create.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ionesculiviucristian picture ionesculiviucristian  路  4Comments

notflip picture notflip  路  3Comments

feliperoan picture feliperoan  路  3Comments

ergonomicus picture ergonomicus  路  3Comments

devingray picture devingray  路  3Comments