[Laravel11] What to do when null or false is obtained from Auth Facade during Middleware processing [Auth::]

Hello, this is Enoki from the System Development Department.
This time, I'd like to talk about the changes to middleware syntax that came with the release of Laravel 11. Many Laravel users are probably aware that when adding custom middleware, it is now written in bootstrap/app.php instead of Kernel.php

I used Auth in the middleware I added arbitrarily, was null or false, and I
was unable to get the intended result, so I would like to write about how to deal with this while comparing Laravel 10 and Laravel 11.

Example of any Middleware you want to add

This is for people who want to add middleware like this!

namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Symfony\Component\HttpFoundation\Response; class HogeMiddleware { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { $user = Auth::user(); // If the user has a specific flag and you want to redirect them to a specific route if ($user->someThingFlag === false) { return redirect()->route('route.something'); } return $next($request);

(This is just an example. If the user cannot retrieve it, an error will occur.)

How to add Middleware: Differences between Laravel 10 and 11

In Laravel 10, if you wanted to add any middleware, you added it to $routeMiddleware in Kernel.php

    /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array<string, class-string|string> */ protected $routeMiddleware = [ 'hoge' => \App\Http\Middleware\HogeMiddleware::class, ];

In this case, I was able to use the Auth facade in the middleware without any problems. (In my own experience)
(I think there are many times when it would be nice to be able to use Auth in middleware.)

So, in Laravel 11, the part that corresponds to this Kenel.php has been changed to app.php, and what happened to its contents?

return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', then: function () { Route::middleware([ 'web', HogeMiddleware::class, ]); } ) ->withMiddleware(function (Middleware $middleware) { $middleware->web(prepend: [ HogeMiddleware::class, ]); }) ->withExceptions(function (Exceptions $exceptions) { // })->create();

It looks like this. It feels like I've had to work on it quite a bit.
To be honest, I'm still not used to it.
If I use it like this, even if I use the Auth facade, I get null or false, so I can't get the authenticated user or anything related to it (or so I thought).

Solution (main topic)

This was also the case in Laravel 10, but it involves setting priority.
In 10, Laravel's default middleware was grouped as follows:

    protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ...

Up until Laravel 10, default middleware was collected in $middlewareGroups.
Custom middleware could be executed in any order by setting $middlewarePriority.
Custom middleware was executed after the standard middleware, so I didn't really care about it.

Upon checking, I found that in order to access user information using Auth, the following two middleware programs must be executed first

\Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Session\Middleware\StartSession::class,

If you use Auth in middleware before these two executions, it seems that you will not be able to obtain the information you intended

For this reason, starting with Laravel 11, we have set priority to actively control the execution order of middleware

    ->withMiddleware(function (Middleware $middleware) { $middleware->priority([ \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Session\Middleware\StartSession::class, \App\Http\Middleware\HogeMiddleware::class, ]); $middleware->web(prepend: [ HogeMiddleware::class, ]); })

Now our Auth facade is ready and we can retrieve data about our user

The end

There's no particular conclusion.
To be honest, I knew that you could control the execution order of middleware in 10, but I didn't actively control it.
You can understand it by reading the official documentation, but I wanted to write more articles like this for Laravel 11 in Japanese, so I wrote this.

If you found this article useful, please click [Like]!
7
Loading...
7 votes, average: 1.00 / 17
923
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Enoki

I play anything, including FPS, RPG, MMO, and crafting