Laravel: "Trying to get property of non-object" 在中间件中使用重定向时

Laravel: "Trying to get property of non-object" when using redirect in middleware

我最近将我的身份验证更改为 Sentinel,除了以下问题之外一切似乎都有效:当用户未通过身份验证时,我想将他重定向到登录页面,但我总是收到错误消息 "Trying to get property of non-object"

我评论了来自Kernel.php的几个标准中间件:

protected $middlewareGroups = [
    'web' => [
        // \Illuminate\Session\Middleware\AuthenticateSession::class,

protected $routeMiddleware = [
    // 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    // 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    // 'can' => \Illuminate\Auth\Middleware\Authorize::class,
    // 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

并且我自己添加了一个新的中间件:

<?php
namespace App\Http\Middleware;
use Closure;
use Sentinel;
class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if (Sentinel::check())
        {
            if (Sentinel::getUser()->roles()->first()->slug == 'admin' ||
                Sentinel::getUser()->roles()->first()->slug == 'superuser' )
            {
                return $next($request);
            }
        }
        else
        {
            return redirect('/login')
            ->with(['error' => "You do not have the permission to enter this site. Please login with correct user."]);
        }
    }
}

如果用户已登录并且我 return 请求,则一切正常。如果用户未登录或级别太低,执行重定向时会触发错误:

"Trying to get property of non-object"

/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php $response->headers->setCookie(

不要在其中使用 else!否则,Sentinel::check() 为真但用户没有正确的 slug 的情况根本不包含在任何 return 值中!

public function handle($request, Closure $next)
    {
        if (Sentinel::check())
        {
            if (Sentinel::getUser()->roles()->first()->slug == 'admin' ||
                Sentinel::getUser()->roles()->first()->slug == 'superuser' )
            {
                return $next($request);
            }
        }

        return redirect('/login')
            ->with(['error' => "You do not have the permission to enter this site. Please login with correct user."]);
    }
}