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

问题描述 投票:0回答:1

这个问题在这里已有答案:

我最近将我的身份验证更改为Sentinel,一切似乎都在以下问题旁边工作:当用户未经过身份验证时,我想将其重定向到登录页面,但我总是收到错误“试图获取非对象的属性“

我评论了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."]);
        }
    }
}

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

“试图获得非对象的属性”

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

php laravel laravel-5 laravel-5.5 laravel-middleware
1个回答
3
投票

不要在那里使用其他人!否则,Sentinel::check()为真但用户没有正确的slugs的情况根本不包含任何返回值!

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."]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.