Is there a way to use Laravel api throttle on individual method inside a controller?

Viewed 1936

I am using api throttle in my routes/api.php (as you can see in the code) but I am wondering if I can use it in the controller on methods.

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

Better to use the routes to specify the middleware for the routes. Still you think to use / specify inside your controller you can define __construct() menthod in your controller like:

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

This will work on the index action of your controller only.

For more details check the documentation Controller Middlewares

you can override route for example

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

//add route after resource

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

second way add condition in controller

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