Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Trying to get property 'headers' of non-object" Middleware\VerifyCsrfToken.php:180

I wrote my custom middleware, but when it is executed, the error appears. Middleware:

namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\Employee;

class CheckConfirm
{
public function handle($request, Closure $next)
{
    if(Auth::check())          
    {
        $id = Auth::id();        
        $empl = Employee::where('user_id','=', $id)->get();
        if($empl->isEmpty())
        {
            return route('confirm');                    
        }
        else
        {                
            dump($empl);
            return $next($request);
        }
    }
    else
    {
        return route('login');
    }
}
}

When I try something like this:

if($empl===null)
   {
      return route('confirm');                    
   }

сondition just doesn't work. In this case, database queries are executed successfully. Here is the error page with dump

like image 221
Vladislav Finder Avatar asked Oct 16 '25 13:10

Vladislav Finder


2 Answers

Your middleware must return a Response object, or $next($request). As written, when not logged in or when $empl is empty, your middleware is just returning a string, not a redirect.

Update your returns to:

return redirect()->route('confirm');

and

return redirect()->route('login');

respectively.

like image 165
patricus Avatar answered Oct 18 '25 09:10

patricus


It is very hard to fix, I tried to do it with App\Http\Middleware\VerifyCsrfToken::except, but not work.

My solution to this problem was creating a redirect to another route using App\Exception\Handler::render method.

if ($exception->getMessage() == "Trying to get property 'headers' of non-object") {
  return redirect()->route('my.default.page');
}
like image 28
Evaldo Barbosa Avatar answered Oct 18 '25 09:10

Evaldo Barbosa