Is there any way to apply rate limit (throttle) for specific method like POST, PUT to prevent multiple api hitting within seconds
I tried to apply limit for whole api in /app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
...
],
'api' => [
'throttle:1,0.008', <<--- its prevent all api within 0.48 sec
],
];
Problem :
we need to prevent only selected methods.
CodePudding user response:
There are number of ways to do it, You can create another middleware which you can use and group the routes you want to apply custom throttle.
Additionally, you can straightly apply the throttle when defining a route
Route::post('/wiggle', function () {
//
})->middleware(['auth:api','throttle:1,0.008']);
or
Route::middleware(['auth:api','throttle:1,0.008'])->group(function () {
Route::post('wiggle', [YourClass::class, 'wiggle'])->name('wiggle');
});
CodePudding user response:
You can use multiple ways to make rate limit in Laravel.
One of ways is Middleware. silver already describe the way.
Second way is using Illuminate\Support\Facades\RateLimiter
(Laravel 8 or higher)
For example, if you want to send email verification messages with rate limit 1 message per 60 seconds.
namespace App\Http\Controllers;
use Illuminate\Support\Facades\RateLimiter;
class EmailVerificationController extends Controller
{
public function send(Request $request)
{
$user = Auth::user();
$email = $request->input('email');
$resendSmsTimeoutSecs = 60;
$rateLimiterKey = 'email-verification:' . $email;
RateLimiter::attempt($rateLimiterKey, 1,
function () use ($user) {
$user->sendEmailVerification();
},
$resendSmsTimeoutSecs
);
return response()->json([
'resend_timeout' => RateLimiter::availableIn($rateLimiterKey)
]);
}
}