Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

betterbrandagency's avatar

Problem accessing $request->user() in my Middleware.

Hi, so I am following along with the video 'Ogres Are Like Middleware' in 'Laravel 5 Fundamentals' and I am having some issues with the 'RedirectIfNotAManager.php' middleware.

This is the code I have and the problem is that $request->user() returns null as opposed to my user so I can't use my isATeamManager() function.

RedirectIfNotAManager.php

<?php

namespace App\Http\Middleware;

use Closure;

class RedirectIfNotAManager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        dd($request->user());
        if (!$request->user()->isATeamManager()){
            return redirect('articles');
        }

        return $next($request);
    }
}

Kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'manager' => \App\Http\Middleware\RedirectIfNotAManager::class,
];

Routes.php

Route::get('foo', ['middleware' => 'manager', function() {
    return 'This page may only be viewed by managers.';
}]);

Update: I managed to fix it by putting the middleware route into the ['middleware' => 'web'] route group.

1 like
5 replies
lara_crass's avatar

6 years later and i was having the same problem. thanks for sharing!

1 like
martinbean's avatar

@lara_crass You need to authenticate the user before you can start dealing with the user, so call the auth middleware before any other middleware that attempts to call $request->user()

2 likes
dev-idkwhoami's avatar

I case someone finds this in Laravel 11 here is the new solution:

$middleware->web(append: [
		YourMiddleware::class
]);
2 likes

Please or to participate in this conversation.