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

Hello, this is Enoki from the Systems Development Department.
Today, I'd like to talk about the changes in middleware syntax that come with the release of Laravel 11. Many Laravel usersKernel.phpinstead ofbootstrap/app.phpare probably aware of the change where you now add your own middleware to

within arbitrarily added middlewarewhere using Authresulted in null or false, preventing
me from obtaining the intended outcome. Therefore, I would like to discuss how to deal with this issue, 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, when adding custom middleware,`Kernel.php`you would add it to `$routeMiddleware` in

    /** * 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, using the Auth facade within the middleware worked without any problems. (Compared to my previous experience)
(I think there are often times when it would be nice to be able to use Auth within 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();

This is what it looks like. It looks like it's been significantly improved... To be
honest, I'm still not very used to it.
If you use it as is, even if you use the Auth facade, you'll get null or false, and you won't be able to retrieve the authenticated user or anything related to them (at least not before).

Solution (main topic)

This was also present in Laravel 10, and it involves setting the priority.
In version 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 grouped into `$middlewareGroups`.
Furthermore, you could arbitrarily change the execution order of custom middleware by setting `$middlewarePriority`.
Since custom middleware was executed after the standard middleware, I never really paid much attention to 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 this.
To be honest, in version 10, I knew you could control the execution order of middleware, but I didn't actively use that control.
You can find out by reading the official documentation, but I wrote this because I wish there were more Japanese articles about Laravel 11.

If you found this article helpful,please give it a "Like"!
7
Loading...
7 votes, average: 1.00 / 17
1,058
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Enoki

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