0

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

Mahdi Rashidi
  • 411
  • 3
  • 8
rzshss
  • 95
  • 1
  • 15
  • 2
    Take a look at `spatie/laravel-permission` docs on extending: https://spatie.be/docs/laravel-permission/v5/advanced-usage/extending – zoltalar Apr 10 '23 at 09:21
  • What are you trying to do? What permssions are you trying to check? – Toby Allen Apr 10 '23 at 10:36
  • In additionally to check if the module_id is also matching. I'm trying to manage same permissions set for different modules in my app. Modules mean main areas of app and it will grow overtime. But they only have the same set of permissions. – rzshss Apr 10 '23 at 10:58
  • Have you looked into Laravel's policies system? – ceejayoz Apr 10 '23 at 11:04
  • Looking onto policies, case is to manage permissions on database rather than built into the code. There are many permissions and might increase when additional functionalities comes. So better to maintain it on the database. – rzshss Apr 10 '23 at 14:12

1 Answers1

1

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.

Mahdi Rashidi
  • 411
  • 3
  • 8
  • 1
    Clever, I like this approach. – ceejayoz Apr 10 '23 at 15:50
  • These modules cannot be hardcoded into the code as they are contained in a table. How can we extend this to use like this. select permission from role_has_permissions where permission_id = requested permision and role_id = user role and module_id = permission checking module; – rzshss Apr 10 '23 at 16:08