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?
I am not sure if that is the thing that you need, but maybe it will help you. I have modular application structure and for each module one route.php file. In that file my routes depend on permission:
Route::get('/edit/{param?}', [
'as' => 'get.users.edit',
'uses' => 'UsersController@getEdit',
'middleware' => ['permission:admin']
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.