【问题标题】:Laravel RedirectIfAuthenticatedLaravel RedirectIfAuthenticated
【发布时间】:2021-01-16 05:11:55
【问题描述】:

我有问题,当用户使用 laravel 6 中的中间件按角色登录到他们的仪表板时,我试图重定向用户。但我被困在这种情况下无法弄清楚问题出在哪里。请帮忙,谢谢。

每个角色都有这个路由web.php

Route::group([ 'as'=>'user.', 'prefix'=>'user', 'namespace'=>'User', 'middleware'=>['auth','user']],
    function(){
        Route::get('dashboard', 'DashboardController@index')->name('dashboard');
});

中间件看起来像

public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->role->id == 3 ) {
            return $next($request);
        }else{
            return redirect()->route('login');
        }
    }

RedirectIfAuthenticated

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check() && Auth::user()->role->id == 1 ) {
            return redirect()->route('admin.dashboard');
        }elseif (Auth::guard($guard)->check() && Auth::user()->role->id == 2) {
            return redirect()->route('author.dashboard');
        }elseif (Auth::guard($guard)->check() && Auth::user()->role->id == 3) {
            return redirect()->route('user.dashboard');
        }else{
            
              return $next($request);
        }

还有LoginController

 public function __construct()
    {
        if (Auth::check() && Auth::user()->role->id == 1  ) {
            $this->redirectTo = route('admin.dashboard');
        }elseif (Auth::check() && Auth::user()->role->id == 2  ) {
            $this->redirectTo = route('author.dashboard');
        }elseif (Auth::check() && Auth::user()->role->id == 3  ) {
            $this->redirectTo = route('user.dashboard');
        } else {
            $this->middleware('guest')->except('logout');
        }


        
    }

【问题讨论】:

  • 在你的构造函数中这样做不会做任何事情......会话还没有开始,所以Auth::check将总是返回false......guest中间件就是那个地方
  • 你能帮我解决一下吗?

标签: php laravel laravel-6


【解决方案1】:

您的第一个中间件检查用户是否已登录以及他是否具有角色 3。

也许改成:

public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            return $next($request);
        }else{
            return redirect()->route('login');
        }
    }

【讨论】:

  • 它工作正常,我猜问题可能在 RedirectIfAuthenticated 或 LoginController..
猜你喜欢
  • 1970-01-01
  • 2016-06-30
  • 2019-01-22
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2017-03-11
  • 2020-07-07
相关资源
最近更新 更多