[Laravel11]middleware
Karnel.phpは無い
下記でapp/Http/Middleware/TestMiddleware.phpを作成する
sail artisan make:middleware TestMiddleware
bootstrap/app.phpに追記する
<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { /** グローバルミドルウェア(すべてのリクエストに適用)先頭に登録 */ $middleware->prepend(TestMiddleware::class); /** グローバルミドルウェア(すべてのリクエストに適用)末尾に登録 */ $middleware->append(TestMiddleware::class); /** Webルート末尾に追加 */ $middleware->web(append: [ TestMiddleware::class, ]); /** APIルート先頭に追加 */ $middleware->api(prepend: [ TestMiddleware::class, ]); }) ->withExceptions(function (Exceptions $exceptions) { // })->create();
特定のルートだけに適用する場合bootstrap/app.phpへの追記は不要
routes/web.php
use App\Http\Middleware\TestMiddleware; Route::get('post/create',[PostController::class,'create'])->middleware(['auth',TestMiddleware::class])->name('post.create');
複数設定する場合
Route::middleware(['auth',TestMiddleware::class])->group(function () { Route::get('post/create',[PostController::class,'create'])->name('post.create'); Route::get('/test',[TestController::class,'test'])->name('test'); });
TestMiddlewareの中身サンプル
public function handle(Request $request, Closure $next): Response { if(auth()->user()->role === 'admin'){ return $next($request); } return redirect()->route('dashboard'); }