イントロダクションIntroduction
HTTPミドルウェアはアプリケーションへ送信されたHTTPリクエストをフィルタリングする、便利なメカニズムを提供します。たとえば、アプリケーションのユーザが認証されているかを確認するミドルウェアがLaravelに用意されています。ユーザが認証されていなければ、このミドルウェアはユーザをログインページへリダイレクトします。反対にそのユーザが認証済みであれば、そのリクエストがアプリケーションのその先へ進むことを許可します。HTTP middleware provide a convenient mechanism for 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 the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
もちろん認証の他にも多彩なタスクを実行するミドルウェアを書くことができます。たとえばCORSミドルウェアは、アプリケーションから返されるレスポンス全部に正しいヘッダを追加することに責任を持つでしょう。ログミドルウェアはアプリケーションにやってきたリクエスト全部をログすることに責任を負うでしょう。Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.
サイトメンテナンスモードや認証、CSRF保護などLaravelには多くのミドルウェアが用意されています。これらのミドルウェアは全部、app/Http/Middleware
ディレクトリに設置されています。There are several middleware
included in the Laravel framework, including
middleware for maintenance, authentication, CSRF
protection, and more. 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 AgeMiddleware
このコマンドにより、AgeMiddleware
クラスが、app/Http/Middleware
ディレクトリー中に生成されます。このミドルウェアで、ageに200歳以上が指定された場合のみ、アクセスを許してみましょう。そうでなければ、ユーザーを"home"のURIへリダイレクトします。This command will place a new
AgeMiddleware
class within your
app/Http/Middleware
directory. In this
middleware, we will only allow access to the route
if the supplied age
is greater than
200. Otherwise, we will redirect the users back to
the "home" URI.
<?php
namespace App\Http\Middleware;
use Closure;
class AgeMiddleware
{
/**
* リクエストフィルターを実行
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('age') <= 200) {
return redirect('home');
}
return $next($request);
}
}
ご覧の通り、age
が200
以下の場合、ミドルウェアはHTTPリダイレクトをクライアントへ返します。そうでなければ、リクエストはパスし、アプリケーションの先へ進めます。ミドルウェアのチェックに合格し、アプリケーションの先へリクエストを通すには、$request
を渡し$next
コールバックを呼び出すだけです。As you can see, if the given
age
is less than or equal to
200
, 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"), simply 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.
Before/AfterミドルウェアBefore / After Middleware
ミドルウェアがリクエストの前、後に実行されるかは、そのミドルウェアの組み方により決まります。次のミドルウェアはアプリケーションによりリクエストが処理される前に実行されます。Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:
<?php
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// なにかアクションを取るコードをここに記述
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;
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
// なにかアクションを取るコードをここに記述
return $response;
}
}
ミドルウェア登録Registering Middleware
グローバルミドルウェアGlobal Middleware
あるミドルウェアをアプリケーションの全HTTPリクエストで実行したい場合は、app/Http/Kernel.php
クラスの$middleware
プロパティへ追加してください。If you want a middleware to be
run during every HTTP request to your application,
simply list the middleware class in the
$middleware
property of your
app/Http/Kernel.php
class.
ミドルウェアをルートへ登録Assigning Middleware To Routes
全ルートに適用するのではなく、特定のルートのみに対しミドルウェアを指定したい場合は、先ずapp/Http/Kernel.php
ファイルでミドルウェアの短縮キーを登録します。デフォルト状態でこのクラスは、Laravelに含まれているミドルウェアのエントリーを$routeMiddleware
プロパティに持っています。ミドルウェアを追加する方法は、選んだキー名と一緒にリストへ付け加えるだけです。If you would like to assign
middleware to specific routes, you should first
assign the middleware a short-hand key in your
app/Http/Kernel.php
file. By default,
the $routeMiddleware
property of this
class contains entries for the middleware included
with Laravel. To add your own, simply append it to
this list and assign it a key of your choosing. For
example:
// App\Http\Kernelクラスの中
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
HTTPカーネルへミドルウェアを定義し終えたら、そのmiddleware
キーをルートのオプション配列で指定できます。Once the middleware has been
defined in the HTTP kernel, you may use the
middleware
key in the route options
array:
Route::get('admin/profile', ['middleware' => 'auth', function () {
//
}]);
ルートに複数のミドルウェアを定義するために配列が使えます。Use an array to assign multiple middleware to the route:
Route::get('/', ['middleware' => ['first', 'second'], function () {
//
}]);
配列を使う代わりに、ルート定義にmiddleware
メソッドをチェーンすることもできます。Instead of using an array, you
may also chain the middleware
method
onto the route definition:
Route::get('/', function () {
//
})->middleware(['first', 'second']);
ミドルウェアを指定する時に、完全なクラス名を指定することもできます。When assigning middleware, you may also pass the fully qualified class name:
use App\Http\Middleware\FooMiddleware;
Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () {
//
}]);
ミドルウェアグループMiddleware Groups
多くのミドルウェアを一つのキーによりまとめ、ルートへ簡単に指定できるようにしたくなることもあります。HTTPカーネルの$middlewareGroups
プロパティにより可能です。Sometimes you may want to group
several middleware under a single key to make them
easier to assign to routes. You may do this using
the $middlewareGroups
property of your
HTTP kernel.
WebのUIとAPIルートへ適用できる、一般的なミドルウェアを含んだ、web
とapi
をLaravelは最初から用意しています。Out of the box, Laravel comes
with web
and api
middleware groups that contains common middleware
you may want to apply to web UI and your API
routes:
/**
* アプリケーションのミドルウェアグループ
*
* @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,
],
'api' => [
'throttle:60,1',
'auth:api',
],
];
ミドルウェアグループは、個別のミドルウェアと同じ記法を使い、ルートやコントローラへ結合します。再度説明しますと、ミドルウェアグループは一度に多くのミドルウエアを簡単に、より便利に割り付けるための方法です。Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups simply make it more convenient to assign many middleware to a route at once:
Route::group(['middleware' => ['web']], function () {
//
});
RouteServiceProvider
により、デフォルトのroutes.php
ファイルでは、web
ミドルウェアグループが自動的に適用されることを覚えておいてください。Keep in mind, the
web
middleware group is automatically
applied to your default routes.php
file
by the RouteServiceProvider
.
ミドルウェアパラメーターMiddleware Parameters
ミドルウェアは追加のカスタムパラメーターを受け取ることができます。たとえば指定されたアクションを実行する前に、与えられた「役割(role)」を持った認証ユーザであるかをアプリケーションで確認する必要がある場合、役割名を追加の引数として受け取るRoleMiddleware
を作成することができます。Middleware can also receive
additional custom 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 a
RoleMiddleware
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;
class RoleMiddleware
{
/**
* リクエストフィルターを実行
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $role
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
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
:
. Multiple parameters should be
delimited by commas:
Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
//
}]);
終了処理ミドルウェアTerminable Middleware
まれにHTTPレスポンスがブラウザに送られた後に、ミドルウェアが何かの作業を行う必要があることもあります。たとえば、Laravelに含まれている「セッション」ミドルウェアは、ブラウザにレスポンスを送った後にストレージへセッションデーターを書き込みます。これを行うにはterminate
メソッドを追加し、終了処理可能な(terminable)としてミドルウェアを定義してください。Sometimes a middleware may need
to do some work after the HTTP response has already
been sent to the browser. For example, the
"session" middleware included with Laravel
writes the session data to storage after
the response has been sent to the browser. To
accomplish this, define the middleware as
"terminable" by adding a
terminate
method to the
middleware:
<?php
namespace Illuminate\Session\Middleware;
use Closure;
class StartSession
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
// セッションデーターの保存
}
}
terminate
メソッドはリクエストとレスポンスの両方を受け取ります。終了処理可能なミドルウェアを定義したら、HTTPカーネルでグローバルミドルウェアのリストへ追加してください。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 global middlewares in
your HTTP kernel.
ミドルウェアのterminate
メソッド呼び出し時に、Laravelはサービスコンテナから真新しいミドルウェアのインスタンスを依存解決します。handle
とterminate
メソッドの呼び出しで同一のミドルウェアインスタンスを使用したい場合は、コンテナのsingleton
メソッドを使用し、ミドルウェアを登録してください。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.