Laravel:在中间件中使用重定向时“试图获取非对象的属性”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46986696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: "Trying to get property of non-object" when using redirect in middleware
提问by titonior
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"
我最近将我的身份验证更改为 Sentinel,除了以下问题之外,一切似乎都有效:当用户未通过身份验证时,我想将他重定向到登录页面,但我总是收到错误“试图获取非对象的属性”
I have commented several standard middleware from the Kernel.php:
我已经评论了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(
“试图获取非对象的属性”
/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php $response->headers->setCookie(
回答by manniL
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!.
不要在那里使用其他!否则,Sentinel::check()
任何返回值都不会涵盖为真但用户没有正确的 slug 的情况!
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."]);
}
}