Laravel中间件返回(试图获取非对象的属性``标头'')错误 [英] Laravel middleware returning (Trying to get property 'headers' of non-object) error

查看:72
本文介绍了Laravel中间件返回(试图获取非对象的属性``标头'')错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将资源路由包装到自定义中间件时出现错误

I'm getting error when I wrap a resource route to my custom 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');
        // }
    }
}

使用中间件的资源路由:

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

我遇到错误:

(试图获取非对象的属性标头").

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

如何解决?

推荐答案

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

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

当您要允许系统继续处理前面的请求时,您执行 return $ next($ request); .

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

但是,如果在 if(Auth :: check()&& Auth :: user()-> role =='title_leg')条件失败的情况下,您没有提到什么系统应该做.

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

如果您不想将页面显示为可用,则可能是 abort(404),或者可能是 abort(403)禁止访问.

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

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 documentation for more options.

这篇关于Laravel中间件返回(试图获取非对象的属性``标头'')错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆