如何覆盖组中间件?我想要实现的是为注册/登录路由添加其他 throttle 限制。
我当前的 throttle 是在内核中设置的。
'api' => [
'throttle:40,1',
'bindings',
],
我想为登录/注册路由设置新的 throttle 限制。
我就是这样做的。
Route::post('login', 'Api\UserController@login')->middleware('throttle:15,3')->name('user.login');
Route::post('register', 'Api\UserController@register')->middleware('throttle:15,3')->name('user.register');
当我运行 php artisan route:list 时,它说这个中间件 api,throttle:15,3 应用于这条路线。
问题是当我运行登录请求时,响应头说
X-RateLimit-Limit 40
X-RateLimit-Remaining 38
所以据我所知,我的新中间件没有被应用。但是我的 throttle 请求被计算了两次。我如何应用不同的中间件来限制登录/注册路由并覆盖旧的?
最佳答案
有同样的问题,只是做了一些研究。似乎没有办法覆盖中间件配置。
我也看到我的中间件已在 route:list
中更新但是在解析中间件时,它总是使用一组合并的规则,因此初始 api
规则最终将覆盖任何定义其他内容的内容。
你有几个选择:
api
中间件定义然后使用 Route::group()
将该特定规则重新添加到其余路由中。然后,在同一个文件中,您可以创建一个新的 Route::group()
它定义了自定义 throttle 配置。Route::group(['middleware' => 'throttle:120,1'], function () {
...
});
Route::group(['middleware' => 'throttle:15,3'], function () {
...
});
api-auth.php
包装在自定义中间件组中的文件,您定义的就像默认的 api
中间件。 (你需要在你的 RouteServiceProvider
中添加另一个调用来加载它:public function map() {
...
$this->mapCustomAuthRoutes();
}
protected function mapCustomAuthRoutes()
{
Route::middleware(['throttle:15,3', 'bindings'])
->namespace($this->namespace)
->as('api.')
->group(base_path('routes/api-auth.php'));
}
关于php - Laravel 覆盖组中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387199/