Search code examples
phplaravellaravel-5laravel-5.8laravel-middleware

Call to a member function setCookie() on null - Laravel 5.8


I have no idea why I keep getting this lately by just simply navigate between pages.

Call to a member function setCookie() on null

This is what I have in my AdminMiddleware

<?php

namespace App\Http\Middleware;

use App\Article;
use Closure, View, Auth ;
use Illuminate\Contracts\Auth\Guard;

class AdminMiddleware
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ( Auth::user()->type !== "Admin") {
            return View::make('layouts.share.errors.404');
        }

        return $next($request);
    }
}

I'm on Laravel 5.8.


Solution

  • The error occurs when you are logged in as a non Admin because you are returning a View in your AdminMiddleware instead of a Response.

    Replace:

    if ( Auth::user()->type !== "Admin") {
        return View::make('layouts.share.errors.404');
    }
    

    With:

    if ( Auth::user()->type !== "Admin") {
        return response()->view('layouts.share.errors.404', [], 404);
    }