Readouble

Laravel 10.x ミドルウェア

イントロダクションIntroduction

ミドルウェアは、アプリケーションに入るHTTPリクエストを検査およびフィルタリングするための便利なメカニズムを提供します。たとえば、Laravelには、アプリケーションのユーザーが認証されていることを確認するミドルウェアが含まれています。ユーザーが認証されていない場合、ミドルウェアはユーザーをアプリケーションのログイン画面にリダイレクトします。逆に、ユーザーが認証されている場合、ミドルウェアはリクエストをアプリケーションへ進めることを許可します。Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

ミドルウェアを追加して、認証以外にもさまざまなタスクを実行できます。たとえば、ログミドルウェアなら、アプリケーションが受信したすべてのリクエストをログへ記録できるでしょう。Laravelフレームワークには、認証やCSRF保護用のミドルウェアなど、ミドルウェアがいくつか含まれています。これらのミドルウェアはすべて、app/Http/Middlewareディレクトリにあります。Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory.

ミドルウェアの定義Defining Middleware

新しいミドルウェアを作成するには、make:middleware Artisanコマンドを使用します。To create a new middleware, use the make:middleware Artisan command:

php artisan make:middleware EnsureTokenIsValid

このコマンドは、新しいEnsureTokenIsValidクラスをapp/Http/Middlewareディレクトリ内に配置します。例としてこのミドルウェアで、リクエストが供給するtoken入力が、指定値と一致する場合にのみ、ルートへのアクセスを許可します。それ以外の場合は、ユーザーをhome URIへリダイレクトしましょう。This command will place a new EnsureTokenIsValid class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied token input matches a specified value. Otherwise, we will redirect the users back to the home URI:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTokenIsValid
{
    /**
     * 受信リクエストの処理
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->input('token') !== 'my-secret-token') {
            return redirect('home');
        }

        return $next($request);
    }
}

ご覧のとおり、与えられたtokenがシークレットトークンと一致しない場合、ミドルウェアはHTTPリダイレクトをクライアントに返します。それ以外の場合、リクエストはさらにアプリケーションに渡されます。リクエストをアプリケーションのより深いところに渡す(ミドルウェアが「パス」できるようにする)には、$requestを使用して$nextコールバックを呼び出す必要があります。As you can see, if the given token does not match our secret token, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), you should call the $next callback with the $request.

ミドルウェアは、HTTPリクエストがアプリケーションに到達する前に通過しなければならない一連の「レイヤー」として考えるのがベストです。各レイヤーはリクエストを検査したり、完全に拒否したりすることができます。It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

lightbulb Note: すべてのミドルウェアはサービスコンテナを介して依存解決されるため、ミドルウェアのコンストラクター内で必要な依存関係をタイプヒントで指定できます。[!NOTE]
All middleware are resolved via the service container[/docs/{{version}}/container], so you may type-hint any dependencies you need within a middleware's constructor.

ミドルウェアとレスポンスMiddleware and Responses

もちろん、ミドルウェアはアプリケーションのより深部へリクエストの処理を委ねるその前後にあるタスクを実行できます。たとえば、次のミドルウェアは、リクエストがアプリケーションによって処理される前にいくつかのタスクを実行します。Of course, a middleware can perform tasks before or after passing the request deeper into the application. For example, the following middleware would perform some task before the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BeforeMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        // アクションの実行…

        return $next($request);
    }
}

一方、このミドルウェアは、リクエストがアプリケーションによって処理された後にそのタスクを実行します。However, this middleware would perform its task after the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AfterMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // アクションの実行…

        return $response;
    }
}

ミドルウェアの登録Registering Middleware

グローバルミドルウェアGlobal Middleware

アプリケーションへのすべてのHTTPリクエスト中であるミドルウェアを実行する場合は、app/Http/Kernel.phpクラスの$middlewareプロパティにそのミドルウェアクラスをリストします。If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.

ルートに対するミドルウェアの指定Assigning Middleware to Routes

特定のルートにミドルウェアを割り当てたい場合は、ルート定義時にmiddlewareメソッドを呼び出してください。If you would like to assign middleware to specific routes, you may invoke the middleware method when defining the route:

use App\Http\Middleware\Authenticate;

Route::get('/profile', function () {
    // ...
})->middleware(Authenticate::class);

ミドルウェア名の配列をmiddlewareメソッドへ渡し、ルートに複数のミドルウェアを割り当てることもできます。You may assign multiple middleware to the route by passing an array of middleware names to the middleware method:

Route::get('/', function () {
    // ...
})->middleware([First::class, Second::class]);

アプリケーションのapp/Http/Kernel.phpファイルで、ミドルウェアにエイリアスを割り当てておくと便利です。デフォルトで、このクラスの$middlewareAliasesプロパティには、Laravelに含まれるミドルウェアのエントリーが含まれています。このリストに自分のミドルウェアを追加して、好きなエイリアスを割り当てられます。For convenience, you may assign aliases to middleware in your application's app/Http/Kernel.php file. By default, the $middlewareAliases property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it an alias of your choosing:

// App\Http\Kernelクラス内…

protected $middlewareAliases = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

HTTPカーネルでミドルウェアのエイリアスを定義したら、ルートにミドルウェアを割り当てるときに、そのエイリアスを使用できます。Once the middleware alias has been defined in the HTTP kernel, you may use the alias when assigning middleware to routes:

Route::get('/profile', function () {
    // ...
})->middleware('auth');

除外ミドルウェアExcluding Middleware

ミドルウェアをルートのグループに割り当てる場合、あるミドルウェアをグループ内の個々のルートに適用しないようにする必要が起きることもあります。これは、withoutMiddlewareメソッドを使用して実行できます。When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method:

use App\Http\Middleware\EnsureTokenIsValid;

Route::middleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/', function () {
        // …
    });

    Route::get('/profile', function () {
        // …
    })->withoutMiddleware([EnsureTokenIsValid::class]);
});

また、ルート定義のグループ全体から特定のミドルウェアのセットを除外することもできます。You may also exclude a given set of middleware from an entire group[/docs/{{version}}/routing#route-groups] of route definitions:

use App\Http\Middleware\EnsureTokenIsValid;

Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/profile', function () {
        // …
    });
});

withoutMiddlewareメソッドはルートミドルウェアのみを削除でき、グローバルミドルウェアには適用されません。The withoutMiddleware method can only remove route middleware and does not apply to global middleware[#global-middleware].

ミドルウェアグループMiddleware Groups

複数のミドルウェアを1つのキーにグループ化して、ルートへの割り当てを容易にしたい場合もあるでしょう。これは、HTTPカーネルの$middlewareGroupsプロパティを使用して実現可能です。Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the $middlewareGroups property of your HTTP kernel.

Laravelは、一般的にWebおよびAPIルートへ適用される可能性のあるミドルウェアをwebおよびapiミドルウェアグループへ予め定義しています。これらのミドルウェアグループは、アプリケーションのApp\Providers\RouteServiceProviderサービスプロバイダによって、対応するwebおよびapiルートファイル内のルートに自動的に適用されることに注意してください。Laravel includes predefined web and api middleware groups that contain common middleware you may want to apply to your web and API routes. Remember, these middleware groups are automatically applied by your application's App\Providers\RouteServiceProvider service provider to routes within your corresponding web and api route files:

/**
 * アプリケーションのルートミドルウェアグループ
 *
 * @var array
 */
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,
    ],

    'api' => [
        \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

ミドルウェアグループは、個々のミドルウェアと同じ構文を使用して、ルートとコントローラアクションに割り当てることができます。繰り返しますが、ミドルウェアグループを使用すると、より便利に一度に多くのミドルウェアをルートに割り当てられます。Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups make it more convenient to assign many middleware to a route at once:

Route::get('/', function () {
    // ...
})->middleware('web');

Route::middleware(['web'])->group(function () {
    // ...
});

lightbulb Note: 最初から、webおよびapiミドルウェアグループは、App\Providers\RouteServiceProviderによってアプリケーションの対応するroutes/web.phpおよびroutes/api.phpファイルへ自動的に適用されます。[!NOTE]
Out of the box, the web and api middleware groups are automatically applied to your application's corresponding routes/web.php and routes/api.php files by the App\Providers\RouteServiceProvider.

ミドルウェアの順序Sorting Middleware

まれに、ミドルウェアを特定の順序で実行する必要があるでしょうが、ルートに割り当てられたときにはミドルウェアの順序を制御できません。この場合、app/Http/Kernel.phpファイルの$middlewarePriorityプロパティを使用してミドルウェアの優先度を指定できます。このプロパティは、デフォルトではHTTPカーネルに存在していません。存在しない場合は、以下のデフォルト定義をコピーしてください。Rarely, you may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In this case, you may specify your middleware priority using the $middlewarePriority property of your app/Http/Kernel.php file. This property may not exist in your HTTP kernel by default. If it does not exist, you may copy its default definition below:

/**
 * ミドルウェアの優先順位でソートされたリスト
 *
 * これにより、非グローバルミドルウェアは常に指定する順序で実行されます。
 *
 * @var string[]
 */
protected $middlewarePriority = [
    \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
    \Illuminate\Cookie\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
    \Illuminate\Contracts\Session\Middleware\AuthenticatesSessions::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];

ミドルウェアのパラメータMiddleware Parameters

ミドルウェアは追加のパラメータを受け取ることもできます。たとえば、アプリケーションが特定のアクションを実行する前に、認証済みユーザーが特定の「役割り(role)」を持っていることを確認する必要がある場合、追加の引数として役割名を受け取るEnsureUserHasRoleミドルウェアを作成できます。Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create an EnsureUserHasRole middleware that receives a role name as an additional argument.

追加のミドルウェアパラメータは、$next引数の後にミドルウェアに渡されます。Additional middleware parameters will be passed to the middleware after the $next argument:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasRole
{
    /**
     * 受信リクエストの処理
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $role): Response
    {
        if (! $request->user()->hasRole($role)) {
            // リダイレクト…
        }

        return $next($request);
    }

}

ミドルウェアのパラメータはルート定義時に、ミドルウェア名とパラメータを「:」で区切って指定します。Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a ::

Route::put('/post/{id}', function (string $id) {
    // ...
})->middleware('role:editor');

複数のパラメーターはコンマで区切る必要があります。Multiple parameters may be delimited by commas:

Route::put('/post/{id}', function (string $id) {
    // ...
})->middleware('role:editor,publisher');

終了処理ミドルウェアTerminable Middleware

HTTPレスポンスがブラウザに送信された後、ミドルウェアが何らかの作業を行う必要がある場合があります。ミドルウェアでterminateメソッドを定義し、WebサーバがFastCGIを使用している場合、レスポンスがブラウザに送信された後、terminateメソッドが自動的に呼び出されます。Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a terminate method on your middleware and your web server is using FastCGI, the terminate method will automatically be called after the response is sent to the browser:

<?php

namespace Illuminate\Session\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TerminatingMiddleware
{
    /**
     * 受信リクエストの処理
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }

    /**
     * レスポンスがブラウザに送信された後にタスクを処理
     */
    public function terminate(Request $request, Response $response): void
    {
        // …
    }
}

terminateメソッドは、リクエストとレスポンスの両方を受信する必要があります。終了処理ミドルウェアを定義したら、それをapp/Http/Kernel.phpファイルのルートまたはグローバルミドルウェアのリストに追加する必要があります。The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of routes or global middleware in the app/Http/Kernel.php file.

ミドルウェアでterminateメソッドを呼び出すと、Laravelはサービスコンテナからミドルウェアの新しいインスタンスを依存解決します。handleメソッドとterminateメソッドが呼び出されたときに同じミドルウェアインスタンスを使用する場合は、コンテナのsingletonメソッドを使用してミドルウェアをコンテナに登録します。通常、これはAppServiceProviderregisterメソッドで実行する必要があります。When calling the terminate method on your middleware, Laravel will resolve a fresh instance of the middleware from the service container[/docs/{{version}}/container]. If you would like to use the same middleware instance when the handle and terminate methods are called, register the middleware with the container using the container's singleton method. Typically this should be done in the register method of your AppServiceProvider:

use App\Http\Middleware\TerminatingMiddleware;

/**
 * 全アプリケーションサービスの登録
 */
public function register(): void
{
    $this->app->singleton(TerminatingMiddleware::class);
}

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作