PHP code example of grazulex / laravel-api-throttle-smart

1. Go to this page and download the library: Download grazulex/laravel-api-throttle-smart 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/ */

    

grazulex / laravel-api-throttle-smart example snippets


// routes/api.php
Route::middleware(['auth:sanctum', 'throttle.smart'])->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/orders', [OrderController::class, 'store']);
});

// config/throttle-smart.php
'plans' => [
    'free' => [
        'label' => 'Free Plan',
        'requests_per_minute' => 60,
        'requests_per_hour' => 500,
        'requests_per_day' => 5000,
        'requests_per_month' => 100000,
        'burst_size' => 10,
        'burst_refill_rate' => 1,
    ],

    'pro' => [
        'label' => 'Pro Plan',
        'requests_per_minute' => 300,
        'requests_per_hour' => 5000,
        'requests_per_day' => 50000,
        'requests_per_month' => 1000000,
        'burst_size' => 50,
        'burst_refill_rate' => 5,
    ],

    'enterprise' => [
        'label' => 'Enterprise Plan',
        'requests_per_minute' => 1000,
        'requests_per_hour' => 20000,
        'requests_per_day' => 200000,
        'requests_per_month' => null, // Unlimited
        'burst_size' => 200,
        'burst_refill_rate' => 20,
    ],
],

use Grazulex\ThrottleSmart\Attributes\RateLimit;
use Grazulex\ThrottleSmart\Attributes\QuotaCost;

class ApiController extends Controller
{
    #[RateLimit(perMinute: 10, perHour: 100)]
    public function sensitiveEndpoint(Request $request)
    {
        // Custom limits for this endpoint
    }

    #[QuotaCost(5)]
    public function expensiveOperation(Request $request)
    {
        // Costs 5 quota units instead of 1
    }
}

use Grazulex\ThrottleSmart\Facades\ThrottleSmart;

// Get rate limits for a user
$limits = ThrottleSmart::getLimits($user);
$limits->minute['remaining']; // 58
$limits->isLimited; // false

// Get quota information
$quota = ThrottleSmart::getQuota($user);
$quota->monthly['remaining']; // 999542
$quota->percentageUsed; // 0.05

// Check without consuming
if (ThrottleSmart::wouldLimit($request)) {
    return response()->json(['message' => 'Please slow down'], 429);
}

// Manually consume quota
ThrottleSmart::consume(5); // Consume 5 units

// Reset limits for a user
ThrottleSmart::reset("user:{$user->id}");

// Grant bonus quota
ThrottleSmart::addQuota($user, 10000, 'Customer support bonus');

'sliding_window' => [
    'enabled' => true,
    'precision' => 1,
],

'token_bucket' => [
    'enabled' => true,
    'initial_tokens' => null, // Start with full bucket
],

use Grazulex\ThrottleSmart\Events\RateLimitExceeded;
use Grazulex\ThrottleSmart\Events\RateLimitApproaching;
use Grazulex\ThrottleSmart\Events\QuotaExceeded;
use Grazulex\ThrottleSmart\Events\QuotaThresholdReached;

// In EventServiceProvider
protected $listen = [
    RateLimitExceeded::class => [
        SendRateLimitNotification::class,
    ],
    QuotaThresholdReached::class => [
        SendQuotaWarningEmail::class,
    ],
];

use Grazulex\ThrottleSmart\Facades\ThrottleSmart;

public function test_rate_limiting(): void
{
    ThrottleSmart::fake();

    // Make requests...

    ThrottleSmart::assertLimitExceeded('user:123');
    ThrottleSmart::assertNotLimited('user:456');
    ThrottleSmart::assertQuotaConsumed(150);
}

public function test_api_is_rate_limited(): void
{
    $user = User::factory()->create(['plan' => 'free']);

    // Make 61 requests (free plan allows 60/min)
    for ($i = 0; $i < 61; $i++) {
        $response = $this->actingAs($user)
            ->getJson('/api/users');
    }

    $response->assertStatus(429)
        ->assertHeader('X-RateLimit-Remaining', '0')
        ->assertJsonPath('error.code', 'RATE_LIMIT_EXCEEDED');
}
bash
php artisan vendor:publish --tag="throttle-smart-config"
bash
php artisan vendor:publish --tag="throttle-smart-migrations"
php artisan migrate
bash
# View rate limit status
php artisan throttle:status

# Check specific user
php artisan throttle:user --user=123

# View analytics
php artisan throttle:analytics --period=day

# Reset user limits
php artisan throttle:reset --user=123

# Reset user quota
php artisan throttle:reset-quota --user=123

# Grant bonus quota
php artisan throttle:grant-quota --user=123 --amount=10000 --reason="Support"

# Cleanup old data
php artisan throttle:cleanup --days=90