Corbin's avatar

Access route parameter in AuthServiceProvider boot method from URL or defer the ability querying to when authorization is actually called?

I've created a role permissions system following the laracast episode: ACL in Laravel: Roles and Permissions. Only difference is that I've added a category to the role_user table.

The goal is to loop through permissions in the boot method in the AuthServiceProvider and only give access to a user if they have the permissions for a specific "category". This would result in me having to obtain the "category_id" from the route parameters. AuthServiceProvider will boot before the Request class so injecting the Request class into AuthServiceProviders boot method would be terrible practice. I have no idea how to get around this though.

#Tables

User

id|name

Roles

id|name|label

Permissions

id|name|label

category_role_user

category_id|role_id|user_id

permissions_role

permision_id|role_id

web.php

Route::get('/test/{category}', function () {

    
    Auth::loginUsingId(3);
    if (Gate::allows('create_post')) {
        return 'works';
    }

});

AuthServiceProvider.php example

public function boot(Request $request)
{
    $this->registerPolicies();

    $category_id = $request->route('channel');
    foreach ($this->getPermissions() as $permission) {


        Gate::define($permission->name, function ($user) use ($permission, $category_id) {
            //Look here!
             return $user->hasPermission($permission, $category_id);
        });
    }
}

protected function getPermissions()
{
    return Permission::with('roles')->get();
}

The code above doesn't even work. category_id is returning null in the query. How do I go about this? I need to get that category_id. The query itself works absolutely fine if I just pass an id in.

My best bet is that I would have to defer defining gates until after the request, but I have absolutely no idea how I would do that.

In the ACL in Laravel: Roles and Permissions video comments Joseph Silber was speaking about :

deferring the ability querying to when authorization is actually called.

So I'm guessing I'll have to do this as well. How do I solve this problem? Thanks for any help I get.

0 likes
1 reply
Corbin's avatar
Corbin
OP
Best Answer
Level 9

I'm doing this totally wrong. I'll just query the Category model each time I want the gate to be implemented.

Gate::define($permission->name, function ($user, $category) use ($permission, $category_id) {

             return $user->hasPermission($permission, $category_id);
        });
}

Please or to participate in this conversation.