phplaravellaravel-permission

getRoleNames method as an accessor in user model. Spatie Laravel Permission


I am trying to create an accessor that will return the users role name. It is possible to access the getRoleNames() method in the User model?

//User Model

/**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'role_name',
    ];

/**
     * Ge the user's role name.
     * 
     * @return Attribute
     */
    public function roleName(): Attribute
    {
        return Attribute::make(
            get: function () {
                $user = User::find($this->id);
                
                return $user->getRoleNames();
            },
        );
    }

I tried to make it as an accessor but it returns null


Solution

  • You need to add following trait in your User model.

    class User extends Authenticatable
    {
       use HasRoles;
    
       // Other model code
       
       // For single role
       public function getRoleNameAttribute()
       {
         return $this->roles->pluck('name')->first();
       }
       
       // For Multiple
       public function getRoleNamesAttribute()
       {
         return $this->roles->pluck('name')->toArray();
       }
    }
    

    Then you can access it easily in your controller like.

    $user = User::find(1);
    $roleName = $user->role_name; // for single
    $roleNames = $user->role_names; // for multiple