Laravel:在中间件中使用重定向时“尝试获取非对象的属性”[重复]

问题描述:

This question already has an answer here:

I recently change my authentication to Sentinel and everything seems to work beside the following problem: when the user is not authenticated, I would like to redirect him to the login page, but I always get an error "Trying to get property of non-object"

I have commented several standard middleware from the 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,

And I have added a new middleware by myself:

<?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."]);
        }
    }
}

In case the user is logged in and I return the request, everything is working well. In case the user is not logged in or have a too low level, there will be an error triggered when the redirect is executed:

"Trying to get property of non-object"

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

</div>

Don't use an else in there! Otherwise, the case that Sentinel::check() is true but the user has not the right slugs isn't covered by any return value at all!.

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."]);
    }
}