自 Laravel 11.34 版本 起,允许开发人员在定义路由时添加条件逻辑。
假如有一个路由中间件 ProductionOnlyMiddleware
,希望在生产环境中才执行,那么可以这样定义路由:
使用命令生成中间件:
php artisan make:middleware ProductionOnlyMiddleware
在定义路由时,添加条件:
use Illuminate\Support\Facades\App;
use Illuminate\Routing\Route as RouteObject;
use App\Http\Middleware\ProductionOnlyMiddleware;
Route::get('/middleware', fn () => 'middleware')
->when(App::isProduction(), fn (RouteObject $route) => $route->middleware(ProductionOnlyMiddleware::class));
# 也可以使用 withoutMiddleware 方法忽略某些中间件
Route::get('/middleware', fn () => 'middleware')
->middleware(ProductionOnlyMiddleware::class)
->when(App::isLocal(), fn (RouteObject $route) => $route->withoutMiddleware(ProductionOnlyMiddleware::class));
另外一个用例是针对不同环境添加或忽略请求次数限制:
Route::get('/limited', fn () => 'limited')
->middleware('throttle:5') # 每分钟最多 5 次请求
->when(App::isLocal(), fn (RouteObject $route) => $route->withoutMiddleware('throttle:5')); # 本地环境忽略请求次数的限制
# 如果确定了只在线上环境使用请求次数限制中间件的话,可以使用下面更简洁的写法
Route::get('/limited', fn () => 'limited')
->when(App::isProduction(), fn (RouteObject $route) => $route->middleware('throttle:5'));