Laravel Tutorials

Reset Rate Limits Dynamically with Laravel's clear Method

Published
Reset Rate Limits Dynamically with Laravel's clear Method image

Laravel's RateLimiter clear method enables dynamic rate limit resets when specific conditions are met, providing flexible control over rate limiting behavior in your applications.

Clear a rate limit programmatically:

use Illuminate\Support\Facades\RateLimiter;
 
RateLimiter::clear('api-calls:' . $userId);

Here's a practical implementation for a file upload system:

class FileUploadController extends Controller
{
public function upload(Request $request)
{
$key = 'file-upload:' . auth()->id();
$limiter = RateLimiter::attempt(
$key,
$perHour = 10,
function() use ($request) {
return FileUpload::create([
'user_id' => auth()->id(),
'filename' => $request->file('document')->store('uploads'),
'size' => $request->file('document')->getSize()
]);
}
);
 
if (!$limiter) {
return response()->json([
'error' => 'Upload limit exceeded. Please wait.'
], 429);
}
 
return response()->json(['status' => 'File uploaded successfully']);
}
 
public function approveUpload(FileUpload $upload)
{
$this->authorize('approve', $upload);
 
$upload->update(['status' => 'approved']);
 
RateLimiter::clear('file-upload:' . $upload->user_id);
 
return response()->json([
'status' => 'Upload approved',
'quota_reset' => true
]);
}
 
public function resetUserQuotas(User $user)
{
RateLimiter::clear('file-upload:' . $user->id);
RateLimiter::clear('bulk-download:' . $user->id);
RateLimiter::clear('share-link:' . $user->id);
 
return back()->with('success', 'Upload quotas reset');
}
}

The clear method provides a way to programmatically reset rate limits when certain conditions are met, making your rate limiting system more dynamic and user-friendly.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article