简体   繁体   English

Laravel 5.5组中间件将您重定向了太多次

[英]Laravel 5.5 group middleware redirected you too many times

I'm trying to write a middleware for a route group to allow only users with is_admin being 1 , but when I access the route, with an user which is and admin, the error message shows up: 我正在尝试为路由组编写中间件,以仅允许is_admin1用户,但是当我使用is和admin用户访问路由时,显示错误消息:

This page isn't working 此页面无效

localhost redirected you too many times. 本地主机将您重定向了太多次。

This is my middleware: 这是我的中间件:

public function handle($request, Closure $next)
{
  if ($request->user()->is_admin === 1) {
    return redirect('/cms');
  }

  return redirect('/contacts');
}

I created a 'cms' key in $middlewareGroups located in Kernel.php : 我在位于Kernel.php $middlewareGroups创建了一个“ cms”键:

'cms' => [
    \App\Http\Middleware\AdminMiddleware::class,
]

And assigned it to my route group: 并将其分配给我的路线组:

Route::group(['middleware' => 'cms'], function() {
  Route::get('/cms', 'CmsController@index')->name('cms');
});

Accessing /contacts works fine, but accessing /cms will result in the error above. 访问/contacts可以正常工作,但是访问/cms将导致上面的错误。

What's happening is this: Your route directs you to the middleware. 这是怎么回事:您的路线将您定向到中间件。 Upon finding that the user is indeed an admin, you use a redirect. 在发现用户确实是管理员后,您可以使用重定向。 As this redirect is through a url, it will use the route, which again uses the middleware. 由于此重定向是通过URL进行的,因此它将使用路由,该路由再次使用中间件。 Effectively, you have created an infinite loop. 实际上,您已经创建了一个无限循环。 What I assume you want to do is to simply continue to what the route points to after the check, like so: 我假设您想做的就是简单地继续检查后路线指向的内容,例如:

return $next($request);

it seems you want to check if the user is admin, and if yes, allow them to the route 'cms'. 似乎您想检查用户是否为admin,如果是,请允许他们进入“ cms”路由。 in that case, you shouldn't use redirect, but simply return true. 在这种情况下,您不应该使用重定向,而只需返回true。

public function handle($request, Closure $next)
{
  if ($request->user()->is_admin === 1) {
    return true;
  }

  return redirect('/contacts');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM