中间件,检查 Laravel 5 后如何重定向

2022-01-02 00:00:00 redirect routes php laravel-5

我需要检查用户是否以编辑者身份登录后,重定向到个人资料页面...

I need after check if user is logged as editor, to redirect to profile page...

这是我的代码:

<?php namespace AppHttpMiddleware;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesRedirect;

use Closure;

class AdminMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()){
                    if(Auth::user()->roles->toArray()[0]['role'] == 'editor'){
                       return redirect('/profile');
                    }
                    return $next($request);
                }
                else
                {

                   return $next($request);
                }
    }

}

此代码的问题是当用户是编辑器时我会无限循环......

Problem with this code is when user is editor I get infinite loop....

这是我的路线:

Route::group(['middleware' => 'auth'], function(){

    Route::get('home', ['middleware' => 'admin', function()
        {
        return view('home');
        }]);
    Route::get('profile', array(
       'as' => 'profile',
       'uses' => 'UserController@getProfile'
    ));


});

有人知道是什么问题吗?

Anyone know what is problem?

推荐答案

你在 AppHttpKernel 中在哪里注册你的中间件?

Where did you register your middleware in AppHttpKernel?

它是否在受保护的 $middleware = []protected $routeMiddleware = [] 中?

Is it in protected $middleware = [] or protected $routeMiddleware = [] ?

如果在 $middleware 中注册,它将在每个请求上运行,从而导致无限循环,如果是这样,则只使用 $routeMiddleware

If registered in $middleware it will run on each very request thereby causing infinite loop, if so use only $routeMiddleware

相关文章