How to resolve Laravel error "Trying to get property 'headers' of non-object"
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
When making a mistake in Laravel Middleware, an error occurs:
Laravel error "Trying to get property 'headers' of non-object"
Here, I write about how to deal with it.
Conclusion
Missing return $next($request);
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return mixed
*/
// public function handle(Request $request, Closure $next, ...$guards)
public function handle()
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
// return $next($request);
}
This is a function in the 'guest' middleware, but if the following line is missing:
return $next($request);
an error occurs (since $request does not go to the next middleware).
Be careful when modifying middleware
When using middleware to change redirection before or after authentication, be sure to be careful when adding if statements.
Other possibilities besides middleware
Since the error is about missing response headers, the same error should occur if there is a problem in any function in the process.
Although I gave one example this time, I think it is highly possible that something other than middleware could be the cause of the error displayed.
Summary
That's all.
I wrote this article because it's a bug that can be difficult to solve if you don't know about it.
Once you know about it, I think it will be easier!
For feedback or complaints, please contact me via Twitter DM.
That's all!
Popular articles
Deploying a PHP7.4 + Laravel6 project to AWS EC2
Implementing breadcrumbs in Laravel with laravel-breadcrumbs