This is more of an academic question than a real-world one, although it stumped me when I came across it in a legacy 5.2 project with misconfigured middleware, and its behavior hasn’t changed in Laravel 11. While similar questions have been asked across the internet, the outcome has always been someone forgetting to move the appropriate middleware before their failing middleware. This is different.
Some context: out of the box, Laravel comes with global, “web”, and “api” middleware groups. Once a user has been authenticated via a regular cookie-based session, the IlluminateCookieMiddlewareEncryptCookies::class
and IlluminateSessionMiddlewareStartSession::class
middlewares are the only ones required to load up that user to be accessed via auth()->user()
or $request->user()
. These middlewares are included as part of the default “web” group.
Middleware is executed sequentially, in the order it is listed. Global middleware is always executed first. However, promoting the aforementioned “web” middleware to global still works, but causes $request->user()
to become null
when referenced from global middleware called just after. In other words:
// app/Http/Middleware/Test.php
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
class Test
{
public function handle(Request $request, Closure $next)
{
dd($request->user()); // `null` when global and `AppModelsUser` when not
dd(auth()->user()); // This always works
}
}
Here’s the rest of the code:
// bootstrap/app.php
<?php
use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationExceptions;
use IlluminateFoundationConfigurationMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
)
->withMiddleware(function (Middleware $middleware) {
// This doesn't work...
$middleware->use([
IlluminateCookieMiddlewareEncryptCookies::class,
IlluminateSessionMiddlewareStartSession::class,
AppHttpMiddlewareTest::class,
]);
$middleware->group('web', []); // Clear out default web middleware
// But this works...
$middleware->use([
IlluminateCookieMiddlewareEncryptCookies::class,
IlluminateSessionMiddlewareStartSession::class,
]);
$middleware->group('web', [
AppHttpMiddlewareTest::class,
]);
// And this also works...
$middleware->use([]); // Clear out default global middleware
$middleware->group('web', [
IlluminateCookieMiddlewareEncryptCookies::class,
IlluminateSessionMiddlewareStartSession::class,
AppHttpMiddlewareTest::class,
]);
})
->create();
// routes/web.php
<?php
use IlluminateSupportFacadesRoute;
Route::get('', fn() => 'It works!');
I did a little digging into Laravel source, but quickly got in over my head. Notably, $request->user()
is always set by the time of this line of StartSession
, regardless if it’s global or not.
I’m satisfied that this behavior is consistent and seemingly intended, but I’m hoping someone more knowledgeable can explain why this behaves this way.