Laravel ミドルウェア
作成
自動生成
php artisan make:middleware MyMiddleware
リクエスト拡張
class MyMiddleware
{
public function handle($request, Closure $next)
{
before処理
リクエストにmsg要素を追加
$request->merge([
’msg’ => ‘Laravel‘
]);
return $next($request);
}
}
class MyMiddleware
{
public function handle($request, Closure $next)
{
before処理
$request->merge([
〜
]);
$response = $next($request);
after処理
$content = $response->content();
$content .= ‘<style>body { background-color: red; }</style>’;
$response->setContent($content);
return $response;
}
}
使用
コントローラでは何もしない
class MyServiceController extends Controller
{
public function index(Request $request)
{
return $request->msg;
→Laravel
}
}
適用
ルーティング設定
※\routes\web.php
use App\Http\Middleware\MyMiddleware;
Route::get(‘/myservice’, [MyServiceController::class, ‘index’])->middleware(MyMiddleware::class);
グローバルミドルウェア
※\routes\web.php
use App\Http\Middleware\MyMiddleware;
Route::get(‘/myservice’, [MyServiceController::class, ‘index’])->middleware(‘test‘);
※\app\Http\Kernel.php
class Kernel extends HttpKernel
{
protected $middlewareGroups = [
’web’ => [
〜
],
’api’ => [
〜
],
’test‘ => [
\App\Http\Middleware\MyMiddleware::class,
],
];
}