PHP code example of philiprehberger / laravel-rate-limiter

1. Go to this page and download the library: Download philiprehberger/laravel-rate-limiter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

philiprehberger / laravel-rate-limiter example snippets


use PhilipRehberger\RateLimiter\Facades\RateLimit;

// Rate limit by arbitrary key
$result = RateLimit::for('global-api')
    ->allow(1000)
    ->perHour()
    ->attempt();

if ($result->denied()) {
    return response()->json(['message' => 'Slow down'], 429, $result->headers());
}

$result = RateLimit::for('api')
    ->allow(100)
    ->perMinute()
    ->attempt();

if ($result->denied()) {
    $seconds = $result->retryAfter(); // e.g. 23

    return response()->json([
        'message' => "Too many requests. Retry in {$seconds} seconds.",
        'retry_after' => $seconds,
        'remaining' => $result->remainingTokens(),
    ], 429, $result->headers());
}

// Arbitrary key
RateLimit::for('some-key');

// Scoped to an authenticated user
RateLimit::forUser($request->user());

// Scoped to an IP address
RateLimit::forIp($request->ip());

RateLimit::for('key')
    ->allow(100)         // max attempts per window (must be >= 1)
    ->perMinute()        // window = 60 seconds (per() 

// 100 requests per 60 seconds, sliding window
Route::middleware('rate-limit:100,60,sliding')->group(function () {
    Route::get('/api/posts', [PostController::class, 'index']);
});

return [
    'default_algorithm' => env('RATE_LIMITER_ALGORITHM', 'sliding'),
    'cache_store'       => env('RATE_LIMITER_CACHE_STORE', null),
    'prefix'            => env('RATE_LIMITER_PREFIX', 'rate_limit'),
];
bash
php artisan vendor:publish --tag=rate-limiter-config