ahmadbadpey's avatar

dynamically permissions based on routes path in larvel via entrust

To create a Role/permission bases laravel app I'm using Zizaco/entrust package.

Now I want to use an approach that no need to assign defined perms to routes as different middlewares in web.php and that is :

First fetches all defined routes (via Route::getRoutes()->getRoutes() ) and store each of them in permissions table.

We can get all routes by this code :

$routes = collect(Route::getRoutes()->getRoutes())->reduce(function ($carry = [], $route) {
           
            $carry[] = $route->uri();
            return $carry;
        });

On the other hand we can define roles that have those permissions and attach those to user in normal way.

Now when a user want to access a page , first we get route path name and then by can method defined in entrust we check that user can access to that route or not. this can done via a simple middleware named checkAccess for example that is added to all routes as a route group. like this :

class checkAccess
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {

           $currentName    =   Route::getCurrentRoute()->getPath();
            if (Auth::user()->can($currentName)) {
                return $next($request);
            }else{
                return response()->view('errors.403', ['prevPage'=> URL::previous()]);
            }*/
            
            return $next($request);

        }
        return Redirect::to('/admin/login');
    }
}

Route::middleware(['checkAccess'])->group(function () {
     //Other routes 
});

But a problem is that some resource routes have same route path but different method access. like:

+-----------+-----------------+---------+----------------+
|  METHOD   |       URL       | Action  |   Route Name   |
+-----------+-----------------+---------+----------------+
| GET       | /photos/{photo} | show    | photos.show    |
| PUT/PATCH | /photos/{photo} | update  | photos.update  |
| DELETE    | /photos/{photo} | destroy | photos.destroy |
+-----------+-----------------+---------+----------------+

And this is cause duplicate permission name Although they are really different in action.

I want to know are there any relative way to create dynamically permission. or what can I do that to solve this problem in this case ?

0 likes
0 replies

Please or to participate in this conversation.