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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article
PhpStorm 2026.2 Released image

PhpStorm 2026.2 Released

Read article
Laravel Doctor: Diagnose Your App With One Artisan Command image

Laravel Doctor: Diagnose Your App With One Artisan Command

Read article
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article