【问题标题】:Is there a way to use Laravel api throttle on individual method inside a controller?有没有办法在控制器内的单个方法上使用 Laravel api 节流?
【发布时间】:2019-11-09 04:14:00
【问题描述】:

我在 routes/api.php 中使用了 api 节流阀(正如您在代码中看到的那样),但我想知道是否可以在方法的控制器中使用它。

Route::resource('/user/{user}/post', 'UserPostController')->middleware(['auth:api', 'throttle:5,1']);

【问题讨论】:

  • 这里有什么问题?您甚至可以为控制器操作的单个路由指定中间件。

标签: php laravel laravel-routing


【解决方案1】:

最好使用路由来指定路由的中间件。您仍然认为在控制器中使用/指定,您可以在控制器中定义__construct() menthod,例如:

public function __construct()
{
    $this->middleware('throttle:5,1')->only('index');
}

这仅适用于控制器的 index 操作。

有关更多详细信息,请查看文档Controller Middlewares

【讨论】:

  • @MarianPopescu 让我知道是否有帮助!
【解决方案2】:

例如,您可以覆盖路线

Route::resource('/user/{user}/post', 'UserPostController')->middleware(['auth:api', 'throttle:5,1']);

//在资源后添加路由

Route::get('/user/create', 'UserPostController@create')->middleware(['auth:api', 'throttle:5,1']);

在控制器中添加条件的第二种方式

public function __construct()
{
   $this->middleware('auth:api');
   $this->middleware('throttle:10,1')->only('create');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2020-01-03
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    相关资源
    最近更新 更多