So I want to give a limit to requests that require a key, and a limit of 100x requests in 60 minutes (for a trial of 10x requests in 5 seconds) and will return (reset) to 0.
but i tried this code, and after 5 seconds the limit is not reset and requests are still limited.
I try this code :
$key = $request->apikey;
$apiKey = ApiKey::where('key', $key)->first();
if (!$apiKey) {
return response()->json(['message' => 'Invalid API key'], 401);
}
$rateLimit = 10;
$timer = 5;
$requests = $apiKey->ignore_limits ?? 0;
$lastRequestTime = Cache::get($key . ':timer');
dd(Cache::has($key));
if ($lastRequestTime && (time() - $lastRequestTime) > ($timer)) {
$requests = 0;
} else {
if ($requests >= $rateLimit) {
return response()->json(['message' => 'Rate limit exceeded'], 429);
}
$requests = $apiKey->ignore_limits ?? $requests;
}
$apiKey->ignore_limits = $requests + 1;
$apiKey->save();
Cache::put($key, $requests, now()->addSeconds($timer));
Cache::put($key . ':timer', time(), now()->addSeconds($timer));
return $next($request);
2
Answers
this my final code works and the descriptions,
I’ve made some adjustments to your code to make it correctly implement rate limiting: