4
1

Laravel11 認証されていないユーザーのリダイレクトの設定方法

Posted at

Laravel11 では、app/Http/Middleware群がフレームワーク側に移動されました。
そのため、認証されていないユーザーのリダイレクトの設定方法を変更する必要があります。

Laravel10 までの認証されていないユーザーのリダイレクトの設定方法

Laravel10 の認証されていないユーザーのリダイレクトの設定方法は、app/Http/Middleware/Authenticate.php
redirectTo メソッドを変更することで行います。

app/Http/Middleware/Authenticate.php
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }
}

Laravel11 の認証されていないユーザーのリダイレクトの設定方法

Laravel11 では、bootstrap/app.phpwithMiddleware でフレームワーク側のミドルウェアを設定します。
認証されていないユーザーのリダイレクトの設定は、redirectGuestsTo メソッドを使用して行います。

bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->redirectGuestsTo('/login');
})

redirectGuestsTo メソッドはクロージャも受け入れます。

bootstrap/app.php
use Illuminate\Http\Request;

->withMiddleware(function (Middleware $middleware) {
    $middleware->redirectGuestsTo(fn (Request $request) => route('login'));
})

管理者用の認証されていないユーザーのリダイレクトの設定方法

ルートグループのルート名を使用して、管理者用の認証されていないユーザーのリダイレクトを設定することもできます。
以下のように、Route::name('admin.') でルートグループを設定が設定されている場合 ...

routes/web.php
Route::name('admin.')->group(function () {
    // ...
});

$request->routeIs('admin.*') で管理者用のルートかどうかを判定し、リダイレクト先を設定します。

bootstrap/app.php
use Illuminate\Http\Request;

->withMiddleware(function (Middleware $middleware) {

    $middleware->redirectGuestsTo(function (Request $request) {

        if ($request->routeIs('admin.*')) {
            return route('admin.login');
        }

        return route('login');
    });
})
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1