Laratrust middleware and blade directives to check from Profile not auth()->user()

729 Views Asked by At

I am getting to know the Laravel framework, and in the test application I am using the santigarcor/laratrust package to implement Roles and permissions. For the project, I assumed that a user may have several profiles (One To Many) with assigned roles and permissions. After logging in, the user is automatically assigned a default profile in the session, which he can change later. For example: User $user has a profiles: manager, editor and reader. Each profile has different roles/permissions. The default profile is the editor. After logging in, I save to Session::put('profile', $user->defaultProfile). If I want to check the roles, e.g. in the controller, I can do:

$profile = Session::get('profile');
$profile->isAbleTo('edit-user');

But if i want to use middleware or blade directives @role(), @permission(), @ability() how to do it? best practice way? Is it possible to easily map these methods so that they check not the user (auth()->user()) but his selected profile? Or I should write custom middleware and blade directives?

1

There are 1 best solutions below

0
On

Since there was no answer here, I read a few and decided to use the built-in Gate functionality. So I can use Gate methods for authorizing abilities (allows, denies, check, any, none, authorize, can, cannot) and the authorization Blade directives (@can, @cannot, @canany).

The gates are defined dynamically:

\App\Models\Permission::get()->map(function($permission) {
    Gate::define($permission->name, function($user) use ($permission) {
        if (session()->has('profile')) {
            $profile = session()->get('profile');
            return optional($profile)->hasPermission($permission->name);
        }
        return false;
    });
});

So for now I think is solved, but I will test it more.