问题描述
我有多个中间件(学生,父母,管理员),并使用该中间件创建了一些路由组.但是,如果用户在任何一个组中并且属于该中间件中的任何一个,则可以访问某些路由,但如果在示例教师中则不在其他中间件中,则可以访问某些路由.我在文档中使用了类似的内容: http://laravel.com/docs/5.1/routing #route-groups 但是,当我放置一条路由时,它是可行的,当使用另一种中间件添加另一个路由组时,它是行不通的.那有可能吗?
I have multi middleware (studen, parent, admin) and create some route group with that middleware. But some route can access if user is in any of that groups and belong in any of that middleware but not if is in other middleware fot example teacher. I use something like that in docs: http://laravel.com/docs/5.1/routing#route-groups But it's work when I put one route, when add another route group with another middleware it doesn't work. Is that possible and how to make it?
当我执行php artisan route时,它给我一个错误
When I execute php artisan route it gives me an error
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function inRole() on null
推荐答案
Laravel的 route中间件按照 routes.php 文件中的声明被一一执行.因此,如果其中一个通过抛出异常或返回一些拒绝来拒绝访问,则不会执行下一个中间件.
Laravel's route middleware is executed one by one as declared in routes.php file. Therefore, if one of them denies access by throwing an exception or returning some respoise, the next middlewares won't be executed.
为了使其正常工作,您将需要一个中间件来检查当前用户是否具有任何必需的角色.幸运的是,从 Laravel 5.1 开始,您可以将参数从 routes.php 文件传递到中间件(请参见 http://laravel.com/docs/5.1/middleware#middleware-parameters ),因此您只需要一个中间件类即可处理所有案例.
In order to make that work, you'll need a single middleware that would check if current user has any of required roles. Luckily, as of Laravel 5.1 you are able to pass parameters to middleware from your routes.php file (see http://laravel.com/docs/5.1/middleware#middleware-parameters), so you'll only need one middleware class to handle all cases.
示例中间件类可能如下所示:
Example middleware class could look like that:
class HasAnyRole
{
public function handle($request, Closure $next, $roles)
{
// Return Not Authorized error, if user has not logged in
if (!$request->user) {
App::abort(401);
}
$roles = explode(',', $roles);
foreach ($roles as $role) {
// if user has given role, continue processing the request
if ($request->user->hasRole($role)) {
return $next($request);
}
}
// user didn't have any of required roles, return Forbidden error
App::abort(403);
}
}
在您的 Kernel.php 中注册中间件:
protected $routeMiddleware = [
'has_any_role' => 'App\Http\Middleware\HasAnyRole',
];
现在,在您的 routes.php 中,您可以将中间件应用于这样的组:
Now, in your routes.php you can apply the middleware to a group like that:
//this route is available only to users with role admin or author
Route::put('post/{id}', ['middleware' => 'has_any_role:admin,author', function ($id) {
//
}]);
这应该可以解决问题,只需确保您的 User 类具有 hasRole 方法.
This should do the trick, just make sure that your User class has a hasRole method.
这篇关于多个中间件在同一路径上具有许可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!