Trying to get 属性 'headers' of non-object (middleware role authentication)

Trying to get property 'headers' of non-object (middleware role authentication)

我想创建两个身份验证角色(管理员和用户)。一切正常,但是例如,当我以用户身份登录并尝试访问管理仪表板时,我想重定向到用户仪表板,而不是因为我不能以用户身份访问它……问题是当我尝试以用户身份访问管理仪表板我收到此错误:Trying to get property 'headers' of non-object

这是我的两个中间件...

管理中间件:

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

用户中间件:

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

我确实为此编辑了 RedirectIfAuthenticated 中间件。

public function handle(Request $request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        /*if (Auth::guard($guard)->check()) {
            return redirect(RouteServiceProvider::HOME);
        }*/

        if (Auth::guard($guard)->check() && Auth::user()->role == 'user') {
            return redirect()->route('user.dashboard');
        }
        elseif (Auth::guard($guard)->check() && Auth::user()->role == 'admin'){
            return redirect()->route('admin.dashboard');
        }
    }

    return $next($request);
}

在中间件中,处理所有情况和return相应的重定向很重要:

return redirect()->route('login');

你应该return重定向
管理中间件:

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

用户中间件:

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