Skip to content

Conflict of HasPermissions trait with Model Role class upon extension #1049

Description

@highstrike

Okay so,

I've extended the Spatie\Permission\Models\Role class to my own App\Models\Role and then also extended the Spatie\Permission\Traits\HasPermissions trait to my own App\Models\Trait\LogHasPermissions

However, when I want to use my own trait in the extended class, like so:

namespace App\Models;

use App\Models\Traits\LogHasPermissions;
use Spatie\Permission\Models\Role as SpatieRole;
use Spatie\Activitylog\Traits\LogsActivity;

class Role extends SpatieRole
{
    use LogsActivity;
    use LogHasPermissions;

I get the following fatal error Declaration of App\Models\Traits\LogHasPermissions::permissions(): Illuminate\Database\Eloquent\Relations\MorphToMany must be compatible with Spatie\Permission\Models\Role::permissions(): Illuminate\Database\Eloquent\Relations\BelongsToMany

Apparently the permissions function defined in the original trait is overwritten in the original role model class (because the function is defined there, therefore it overwrites the trait).

So extending the class and using my own trait (while not having the function defined because i was expecting it from the parent) will use the function from the trait instead, resulting in the above error.

I can avoid the error by also defining a permissions function in my own role class like so

public function permissions(): BelongsToMany {
    return parent::permissions();
}

But surely there must be a better way to do this?
Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions