permissions method in laravel and spatie and user table conflicting with each other

1.3k Views Asked by At

We are using laravel spatie permissions as the library to manage the role and permissions. Unfortunately before implementation of this library we were having a column in user table as permissions where we were managing the permissions. But now when we implemented this library it is getting conflicted with the library. We tried renaming the existing column that works fine for the library. But implementing this at complete project is impossible as there is full flow working on existing column.

Db structure

when tryng to access the permissions of role :

$role->permissions

It returns the current db value and that make checking permission impossible. Can anyone please help me how we canoverride the function in the library of any workaround this.

2

There are 2 best solutions below

1
On

Just change laravel/spatie functions name.

Step 1: Creating a Trait

Inside our app directory, let’s create a new directory and name it Permissions and create a new file namely HasPermissionsTrait.php. A nice little trait has been set up to handle user relations. Back in our User model, just import this trait and we’re good to go.

app/User.php

namespace App;

use App\Permissions\HasPermissionsTrait;

class User extends Authenticatable
{
    use HasPermissionsTrait; //Import The Trait
}

Now go to HasPermissionsTrait.php and add this to it.

App/Permissions/HasPermissionsTrait.php

public function userRolePermissions()
{
    return $this->belongsToMany(Permission::class,'users_permissions');
}

Now change permissions to userRolePermissions and wherever uses it. And now we can access using $user->userRolePermissions with Laravel Eloquent User.

0
On

In Prerequisites Section , In the Installation instructions you'll see that the HasRoles trait must be added to the User model to enable this package's features.

Thus, a typical basic User model would have these basic minimum requirements:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
use HasRoles;

// ..
}