イントロダクション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.
A variety of middleware are included in Laravel,
including middleware for authentication and CSRF
protection; however, all user-defined middleware are
typically located in your application's
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.
サービスコンテナを介して依存解決されるため、ミドルウェアのコンストラクター内で必要な依存関係をタイプヒントで指定できます。[!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リクエストを受診するたび、ミドルウェアを実行したい場合は、アプリケーションのbootstrap/app.php
ファイルにあるグローバルミドルウェアスタックにミドルウェアを追加します:If you want a middleware to run
during every HTTP request to your application, you
may append it to the global middleware stack in your
application's bootstrap/app.php
file:
use App\Http\Middleware\EnsureTokenIsValid;
->withMiddleware(function (Middleware $middleware) {
$middleware->append(EnsureTokenIsValid::class);
})
withMiddleware
クロージャへ渡す$middleware
オブジェクトは、Illuminate\Foundation\Configuration\Middleware
インスタンスで、アプリケーションのルートへ割り当てたミドルウェアを管理します。append
メソッドは、ミドルウェアをグローバルミドルウェアリストの最後に追加します。ミドルウェアをリストの先頭に追加したい場合は、prepend
メソッドを使うべきです。The $middleware
object provided to the withMiddleware
closure is an instance of
Illuminate\Foundation\Configuration\Middleware
and is responsible for managing the middleware
assigned to your application's routes. The
append
method adds the middleware to
the end of the list of global middleware. If you
would like to add a middleware to the beginning of
the list, you should use the prepend
method.
Laravelのデフォルトグローバルミドルウェアの手作業による管理Manually Managing Laravel's Default Global Middleware
Laravelのグローバルミドルウェアスタックを手作業で管理したい場合は、use
メソッドへLaravelのデフォルトのグローバルミドルウェアスタックを指定します。その後、必要に応じてデフォルトのミドルウェアスタックを調整してください。If you would like to manage
Laravel's global middleware stack manually, you may
provide Laravel's default stack of global middleware
to the use
method. Then, you may adjust
the default middleware stack as
necessary:
->withMiddleware(function (Middleware $middleware) {
$middleware->use([
// \Illuminate\Http\Middleware\TrustHosts::class,
\Illuminate\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::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\EnsureTokenIsValid;
Route::get('/profile', function () {
// ...
})->middleware(EnsureTokenIsValid::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]);
除外ミドルウェア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つのキーでグループ化したいことがあります。その場合はアプリケーションのbootstrap/app.php
ファイルで、appendToGroup
メソッドを使ってください。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 appendToGroup
method within
your application's bootstrap/app.php
file:
use App\Http\Middleware\First;
use App\Http\Middleware\Second;
->withMiddleware(function (Middleware $middleware) {
$middleware->appendToGroup('group-name', [
First::class,
Second::class,
]);
$middleware->prependToGroup('group-name', [
First::class,
Second::class,
]);
})
ミドルウェアグループは、個々のミドルウェアと同じ構文を使用して、ルートとコントローラアクションへ指定できます。Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware:
Route::get('/', function () {
// ...
})->middleware('group-name');
Route::middleware(['group-name'])->group(function () {
// ...
});
LaravelのデフォルトミドルウェアグループLaravel's Default Middleware Groups
Laravelには定義済みのweb
ミドルウェアグループとapi
ミドルウェアグループがあり、WebルートとAPIルートへ適用する一般的なミドルウェアを用意しています。Laravelはこれらのミドルウェアグループをroutes/web.php
とroutes/api.php
ファイルに対応して、自動的に適用します。Laravel includes predefined
web
and api
middleware
groups that contain common middleware you may want
to apply to your web and API routes. Remember,
Laravel automatically applies these middleware
groups to the corresponding
routes/web.php
and
routes/api.php
files:
web ミドルウェアグループThe web
Middleware Group |
---|
Illuminate\Cookie\Middleware\EncryptCookies Illuminate\Cookie\Middleware\EncryptCookies |
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse |
Illuminate\Session\Middleware\StartSession Illuminate\Session\Middleware\StartSession |
Illuminate\View\Middleware\ShareErrorsFromSession Illuminate\View\Middleware\ShareErrorsFromSession |
Illuminate\Foundation\Http\Middleware\ValidateCsrfToken Illuminate\Foundation\Http\Middleware\ValidateCsrfToken |
Illuminate\Routing\Middleware\SubstituteBindings Illuminate\Routing\Middleware\SubstituteBindings |
api ミドルウェアグループThe api
Middleware Group |
---|
Illuminate\Routing\Middleware\SubstituteBindings Illuminate\Routing\Middleware\SubstituteBindings |
これらのグループの前後へミドルウェアを追加したい場合は、アプリケーションのbootstrap/app.php
ファイル内でweb
メソッドとapi
メソッドを使用してください。web
メソッドとapi
メソッドは、appendToGroup
メソッドに代わる便利なメソッドです。If you would like to append or
prepend middleware to these groups, you may use the
web
and api
methods within
your application's bootstrap/app.php
file. The web
and api
methods are convenient alternatives to the
appendToGroup
method:
use App\Http\Middleware\EnsureTokenIsValid;
use App\Http\Middleware\EnsureUserIsSubscribed;
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
EnsureUserIsSubscribed::class,
]);
$middleware->api(prepend: [
EnsureTokenIsValid::class,
]);
})
Laravelのデフォルトミドルウェアグループのエントリを、独自のカスタムミドルウェアへ置き換えることもできます。You may even replace one of Laravel's default middleware group entries with a custom middleware of your own:
use App\Http\Middleware\StartCustomSession;
use Illuminate\Session\Middleware\StartSession;
$middleware->web(replace: [
StartSession::class => StartCustomSession::class,
]);
あるいは、ミドルウェアを完全に削除することもできます。Or, you may remove a middleware entirely:
$middleware->web(remove: [
StartSession::class,
]);
Laravelのデフォルトミドルウェアグループを手作業で管理Manually Managing Laravel's Default Middleware Groups
Laravelのデフォルトのweb
ミドルウェアグループとapi
ミドルウェアグループ内のすべてのミドルウェアを手作業で管理したい場合は、グループを完全に再定義してください。以下の例は、web
ミドルウェアグループとapi
ミドルウェアグループをデフォルトのミドルウェアで定義し、必要に応じてカスタマイズできるようにしています。If you would like to manually
manage all of the middleware within Laravel's
default web
and api
middleware groups, you may redefine the groups
entirely. The example below will define the
web
and api
middleware
groups with their default middleware, allowing you
to customize them as necessary:
->withMiddleware(function (Middleware $middleware) {
$middleware->group('web', [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
]);
$middleware->group('api', [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
// 'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);
})
Note: デフォルトでは、
bootstrap/app.php
ファイルにより、web
とapi
ミドルウェアグループがアプリケーションの対応するroutes/web.php
とroutes/api.php
ファイルへ自動的に適用されます。[!NOTE]
By default, theweb
andapi
middleware groups are automatically applied to your application's correspondingroutes/web.php
androutes/api.php
files by thebootstrap/app.php
file.
ミドルウェアエイリアスMiddleware Aliases
アプリケーションのbootstrap/app.php
ファイルで、ミドルウェアへエイリアスを割り当てられます。ミドルウェアのエイリアスを使うと、指定するミドルウェアクラスに対して、短いエイリアス名を定義できます。You may assign aliases to
middleware in your application's
bootstrap/app.php
file. Middleware
aliases allows you to define a short alias for a
given middleware class, which can be especially
useful for middleware with long class
names:
use App\Http\Middleware\EnsureUserIsSubscribed;
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'subscribed' => EnsureUserIsSubscribed::class
]);
})
ミドルウェアのエイリアスをアプリケーションのbootstrap/app.php
ファイルで定義したら、ミドルウェアをルーティングに割り当てるときにエイリアスを使えます。Once the middleware alias has
been defined in your application's
bootstrap/app.php
file, you may use the
alias when assigning the middleware to
routes:
Route::get('/profile', function () {
// ...
})->middleware('subscribed');
便利なように、Laravelの組み込みミドルウェアのいくつかは、デフォルトでエイリアスを定義しています。例えば、auth
ミドルウェアはIlluminate\Auth\Middleware\Authenticate
ミドルウェアのエイリアスです。下記は、デフォルトミドルウェアのエイリアスのリストです。For convenience, some of
Laravel's built-in middleware are aliased by
default. For example, the auth
middleware is an alias for the
Illuminate\Auth\Middleware\Authenticate
middleware. Below is a list of the default
middleware aliases:
エイリアスAlias | ミドルウェアMiddleware |
---|---|
auth auth |
Illuminate\Auth\Middleware\Authenticate Illuminate\Auth\Middleware\Authenticate |
auth.basic auth.basic |
Illuminate\Auth\Middleware\AuthenticateWithBasicAuth Illuminate\Auth\Middleware\AuthenticateWithBasicAuth |
auth.session auth.session |
Illuminate\Session\Middleware\AuthenticateSession Illuminate\Session\Middleware\AuthenticateSession |
cache.headers cache.headers |
Illuminate\Http\Middleware\SetCacheHeaders Illuminate\Http\Middleware\SetCacheHeaders |
can can |
Illuminate\Auth\Middleware\Authorize Illuminate\Auth\Middleware\Authorize |
guest guest |
Illuminate\Auth\Middleware\RedirectIfAuthenticated Illuminate\Auth\Middleware\RedirectIfAuthenticated |
password.confirm password.confirm |
Illuminate\Auth\Middleware\RequirePassword Illuminate\Auth\Middleware\RequirePassword |
precognitive precognitive |
Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests |
signed signed |
Illuminate\Routing\Middleware\ValidateSignature Illuminate\Routing\Middleware\ValidateSignature |
subscribed subscribed |
\Spark\Http\Middleware\VerifyBillableIsSubscribed \Spark\Http\Middleware\VerifyBillableIsSubscribed |
throttle throttle |
Illuminate\Routing\Middleware\ThrottleRequests
or
Illuminate\Routing\Middleware\ThrottleRequestsWithRedis Illuminate\Routing\Middleware\ThrottleRequests
or
Illuminate\Routing\Middleware\ThrottleRequestsWithRedis |
verified verified |
Illuminate\Auth\Middleware\EnsureEmailIsVerified Illuminate\Auth\Middleware\EnsureEmailIsVerified |
ミドルウェアの順序Sorting Middleware
まれに、ミドルウェアを特定の順番で実行する必要があるけれども、ルート指定時に順番を制御できないことがあります。このような状況では、アプリケーションの
bootstrap/app.php
ファイルで、priority
メソッドを使用して、ミドルウェアの優先順位を指定してください。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 these situations, you may specify
your middleware priority using the
priority
method in your application's
bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) {
$middleware->priority([
\Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::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
メソッドはリクエストとレスポンスの両方を受け取る必要があります。終了処理ミドルウェアを定義したら、アプリケーションのbootstrap/app.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 your application's
bootstrap/app.php
file.
ミドルウェアでterminate
メソッドを呼び出すと、Laravelはサービスコンテナからミドルウェアの新しいインスタンスを依存解決します。handle
メソッドとterminate
メソッドが呼び出されたときに同じミドルウェアインスタンスを使用する場合は、コンテナのsingleton
メソッドを使用してミドルウェアをコンテナに登録します。通常、これはAppServiceProvider
のregister
メソッドで実行する必要があります。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);
}