Laravel spatie/laravel-permission extending 'can' function to search additional column

543 Views Asked by At

I have updated the role_has_permissions table with additional column. I need to check this column when checking a permission (Basically extending "can" function as below). Is this even possible?

$user->can('CREATE_INVOICE','MODULE_ID');

Also to extend 'givePermissionTo' function.

$role->givePermissionTo('PRINT_INVOICE','MODULE_ID');

Eg: One User role will have "Manage billing on Car Rentals", but does not have "Manage billing on Bus rentals". Same permission called "Manage billing".

enter image description here

1

There are 1 best solutions below

2
Mahdi Rashidi On

You can use Teams permissions feature to check the modules: Team Permissions

In config/permission.php file:

'teams' => true,
'team_foreign_key' => 'module_id'

Create a middleware to set the module_id:

namespace App\Http\Middleware;

class ModulePermission{
    
    public function handle($request, \Closure $next){
        if(!empty(auth()->user())){
            // session value set on login
            setPermissionsTeamId(session('module_id'));
        }
        // other custom ways to get team_id
        /*if(!empty(auth('api')->user())){
            // `getTeamIdFromToken()` example of custom method for getting the set team_id 
            setPermissionsTeamId(auth('api')->user()->getTeamIdFromToken());
        }*/
        
        return $next($request);
    }
}

Add the middleware to request lifecycle and that's it.

If you already ran migrations for the package, you need to add a custom migration to add module_id to models_has_roles, roles, models_has_permissions and permissions tables.