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
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');
'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');
}