Laravel 中间件返回(试图获取非对象的属性“标题”)错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54643562/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:16:43  来源:igfitidea点击:

Laravel middleware returning (Trying to get property 'headers' of non-object) error

laravelmiddleware

提问by MorshedSaif

I'm getting errorwhen I wrap a resource route to my custom middleware

我得到的错误,当我换一个资源路线我的自定义中间件

My middleware:

我的中间件

<?php

 namespace App\Http\Middleware;

 use Closure;
 use Auth;

class Officer
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->role == 'title_officer') {
            return $next($request);
        }
        // elseif (Auth::check() && Auth::user()->role == 'agent') {
        //     return redirect('/agent');
        // }
        // else {
        //     return redirect('/customer');
        // }
    }
}

The resource routeusing the middleware:

使用中间件的资源路由

Route::resource('new-order', 'BackendController')->middleware('officer');

I'm getting error:

我收到错误:

(Trying to get property 'headers' of non-object).

(试图获取非对象的属性“标题”)。

How to fix it ?

如何解决?

回答by Mihir Bhende

In middleware, it is important to handle all cases and return the redirects accordingly or abort.

在中间件中,重要的是处理所有情况并相应地返回重定向或中止。

You do return $next($request);when you want to allow system to continue processing the request ahead.

return $next($request);当您希望允许系统继续提前处理请求时,您可以这样做。

However, if in case if (Auth::check() && Auth::user()->role == 'title_officer')condition fails, you have not mentioned what system should do.

但是,如果if (Auth::check() && Auth::user()->role == 'title_officer')条件失败,您没有提到系统应该做什么。

You can may be abort(404)if you do not want to show the page as available or maybe abort(403)for access forbidden.

abort(404)如果您不想将页面显示为可用或可能abort(403)禁止访问,您可以这样做。

public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->role == 'title_officer') {
            return $next($request);
        }
        abort(403);
    }

But make sure you do not add a case which will make an infinite loop. Please check documentationfor more options.

但请确保不要添加会造成无限循环的案例。请查看文档以获取更多选项。

回答by Kapitan Teemo

try adding an elseblock which returns when your ifcondition isn't met:

尝试添加一个elseif不满足条件时返回的块:

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