如何在中间件中正确使用Auth:user()?

时间:2019-06-19 12:48:16

标签: laravel laravel-5

如果用户具有“老师”角色,则需要重定向到注销。我试图用中间件来做,但是我不知道这里是什么问题。它说

  

此页面无法正常工作127.0.0.1重定向您太​​多次。

,有时 Auth:user()为空,我想不到。

中间件:

public function handle($request, Closure $next)
    {
        if (Auth::user()->role == User::ROLE_TEACHER) {
            return redirect()->route('logout');
        }
        return $next($request);
    }

内核:

protected $routeMiddleware = [
       .....
        'noTeacher' => \App\Http\Middleware\RedirectIfTeacher::class,

    ];

HomeController:

$this->middleware('noTeacher', ['only' => 'index']);

路线:

Route::post('login', 'Auth\LoginController@login');
Route::get('logout', 'Auth\LoginController@logout')->name('logout');

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

1 个答案:

答案 0 :(得分:0)

可以尝试一下吗?其MiddleWare

class CheckPaAuth {
    public function handle($request, Closure $next) {
        if (Auth::check()) {
            if (Auth::user()->role == "Parent") {
                return $next($request);
            } else {
                auth()->logout();
                return redirect("login")->withErrors(['Login failed,please try again!']);
            }
        } 
        return redirect("login")->withErrors(['Please first login.']);
    }
}

及其Kernel.php

protected $routeMiddleware = [
    'AuthParent' => \App\Http\Middleware\CheckPaAuth::class,
];

及其web.php

Route::group(['middleware' => ['AuthParent'], 'prefix' => 'parent'], function() {
    Route::get('profile', 'UserController@edit');
});