Rate Limiter Utility

The RateLimiterUtil in the LaraUtilX package provides functionality for rate limiting requests.

Method

  1. attempt(string $key, int $maxAttempts, int $decayMinutes): bool: Attempts to hit the given rate limiter.

Usage

  1. Attempt Rate Limiting: To attempt rate limiting, use the attempt method:

    use omarchouman\LaraUtilX\Utilities\RateLimiterUtil;
    
    class MyController extends Controller
    {
       public function index(Request $request)
       {
           $key = 'user:' . $request->user()->id; // Rate limiter key
           $maxAttempts = 10; // Maximum number of attempts
           $decayMinutes = 1; // Decay time in minutes
    
           if (!RateLimiterUtil::attempt($key, $maxAttempts, $decayMinutes)) {
               // Rate limit exceeded
               return response()->json(['error' => 'Too many attempts.'], 429);
           }
    
           // Proceed with the request
       }
    }

Result

The utility returns a boolean value indicating whether the request was successfully rate limited.

  • Success Result: Returns true if the request is within the rate limit and was successfully hit. The request can proceed.

  • Failure Result: Returns false if the rate limit for the specified key has been exceeded. The request should be denied or throttled.

Publish

You can publish this utility through the below command:

php artisan vendor:publish --tag=lara-util-x-rate-limiter



This utility simplifies the process of implementing rate limiting for controlling the rate of requests to an application or API.