0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel 9】複数のMiddlewareと実行の優先度を指定する

Posted at

ミドルウェアとは..?

リクエスト処理の前後に実行したい処理を定義できる機能!

ミドルウェアの作成

artisanコマンドで作成できる。

php artisan make:middleware Hoge

処理を書く

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Hoge
{
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
	 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
	 */
	public function handle(Request $request, Closure $next)
	{
		// リクエストが処理される前の処理を書きたい場合はここに書く
		return $next($request);
        // リクエストが処理された後の処理を書きたい場合はここに書く
	}
}

app/Http/Kernel.php に作ったミドルウェアを追加

Kernel.php
// どのページでも使用したいミドルウェアはここに書く
protected $middleware = [
	// \App\Http\Middleware\TrustHosts::class,
	\App\Http\Middleware\TrustProxies::class,
    // ...
];
Kernel.php
// ルートのグループごとに使用したいミドルウェアはここに書く
protected $middlewareGroups = [
	'web' => [
		\App\Http\Middleware\EncryptCookies::class,
        // ...
    ],

	'api' => [
        // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
		'throttle:api',
		\Illuminate\Routing\Middleware\SubstituteBindings::class,
	],
];
Kernel.php
// ルートごとに指定したいミドルウェアはここに書く
// 今回はここに追加
protected $routeMiddleware = [
	'hoge' => \App\Http\Middleware\Hoge::class,
	'fuga' => \App\Http\Middleware\Fuga::class,
	'piyo' => \App\Http\Middleware\Piyo::class,
];

ミドルウェアの順序を指定

Kernel.php
// ここで指定した順にミドルウェアが実行される。
protected $middlewarePriority = [
	\App\Http\Middleware\Fuga::class,
	\App\Http\Middleware\Piyo::class,
	\App\Http\Middleware\Hoge::class,
];

複数のミドルウェアをroutesに設定する

routes/api.php
// ['Hoge', 'Fuga', 'Piyo'] の順で設定しているが、 $middlewarePriority に指定した順序が適用される
Route::group(['middleware' => ['Hoge', 'Fuga', 'Piyo']], function($router) {
	$router->apiResource('members', MemberController::class, ['only' => ['store', 'show']]);
	$router->apiResource('shops', ShopController::class, ['only' => ['index']]);
	$router->apiResource('blogs', BlogController::class, ['only' => ['index']]);
    // ...
});
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?