Search code examples
laravellaravel-permission

Laravel Spatie Permissions - how to change default model 'role' by another model


please how can i change the default model 'role' by another model in my project (laravel project) has the same architecture as 'role'; the default model package.

in the config/permission.php config file contains:

'models' => [

    /*
     * When using the "HasPermissions" trait from this package, we need to know which
     * Eloquent model should be used to retrieve your permissions. Of course, it
     * is often just the "Permission" model but you may use whatever you like.
     *
     * The model you want to use as a Permission model needs to implement the
     * `Spatie\Permission\Contracts\Permission` contract.
     */

    'permission' => Spatie\Permission\Models\Permission::class,

    /*
     * When using the "HasRoles" trait from this package, we need to know which
     * Eloquent model should be used to retrieve your roles. Of course, it
     * is often just the "Role" model but you may use whatever you like.
     *
     * The model you want to use as a Role model needs to implement the
     * `Spatie\Permission\Contracts\Role` contract.
     */

    'role' => Spatie\Permission\Models\Role::class,

],

i want to have something like this:

'role' => App\Fonction::class,

the documentation says that i have to implement the Spatie\Permission\Contracts\Role` contract. any idea how can i do this in the right way.

the Fonction Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Fonction extends Model
{

    protected $fillable = [
        'nom','description'
    ];


    public function comptes()
    {
        return $this->hasMany('App\Compte') ;
    }

}

Solution

  • You can extend Spatie\Permission\Models\Role class. It already implements Spatie\Permission\Contracts\Role interface. Check details in doc.

    <?php
    
    namespace App;
    
    use Spatie\Permission\Models\Role;
    
    class Fonction extends Role
    {
    
        protected $fillable = [
            'nom','description'
        ];
    
    
        public function comptes()
        {
            return $this->hasMany('App\Compte') ;
        }
    
    }