### Install Laravel Quota via Composer Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Run this command in your terminal to add the package to your Laravel project. ```bash composer require zaber-dev/laravel-quota ``` -------------------------------- ### Schedule Model Pruning Source: https://github.com/zaber-dev/laravel-quota/blob/main/LEARN.md Example command for scheduling the automatic cleanup of prunable models. ```php Schedule::command('model:prune', ['--model' => Quota::class])->daily() ``` -------------------------------- ### Resolved Storage Key Format Source: https://github.com/zaber-dev/laravel-quota/blob/main/LEARN.md Example of the generated cache or database key string used for tracking quota usage. ```php // Resolved Cache/DB Key: "quotas:pdf_exports:App\Models\User:12:1782864000:1785542399" ``` -------------------------------- ### Publish Configuration and Migrations Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Publish the package assets to your application directory. ```bash php artisan vendor:publish --provider="ZaberDev\Quota\QuotaServiceProvider" ``` -------------------------------- ### Configuring Storage Backends Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Specify storage drivers dynamically for quota consumption to optimize performance or data persistence. ```php // Store high-frequency API checks in fast cache/Redis Quota::for('api_ping', $ip)->using('cache')->limit(5000)->perDay()->consume(); // Store critical billing tier budgets in SQL database Quota::for('monthly_exports', $user)->using('database')->limit(50)->perMonth()->consume(); ``` -------------------------------- ### Run Database Migrations Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Execute migrations if using the database storage backend. ```bash php artisan migrate ``` -------------------------------- ### Configure Quota Settings Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Define storage backends and event behavior in config/quotas.php. ```php return [ /* |-------------------------------------------------------------------------- | Default Quota Driver |-------------------------------------------------------------------------- | | Supported drivers: "cache", "database" | */ 'default' => env('QUOTA_DRIVER', 'cache'), 'drivers' => [ 'cache' => [ 'driver' => 'cache', 'store' => env('QUOTA_CACHE_STORE', null), 'prefix' => 'quotas:', ], 'database' => [ 'driver' => 'database', 'table' => 'quotas', ], ], 'events' => [ 'dispatch' => true, ], ]; ``` -------------------------------- ### Consume and check quota usage Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Demonstrates how to consume a quota for a specific user and check the remaining capacity. ```php Quota::for('monthly_exports', $user) ->limit(50) ->perMonth() ->consume(); echo Quota::for('monthly_exports', $user) ->remaining(); ``` -------------------------------- ### Set and Consume Quotas Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Use the Quota facade to define limits and consume units. ```php use ZaberDev\Quota\Facades\Quota; $builder = Quota::for('api_queries', $user) ->limit(1000) ->perDay(); // Available periods: perMinute(), perHour(), perDay(), perWeek(), perMonth(), perYear(), period($start, $end) // Check current usage stats $used = $builder->used(); // int (e.g. 240) $remaining = $builder->remaining(); // int (e.g. 760) $isExceeded = $builder->isExceeded(); // bool (false) $hasCapacity = $builder->hasCapacity(10); // bool (true) // Consume quota (throws QuotaExceededException with HTTP 429 if insufficient capacity) $info = $builder->consume(5); ``` -------------------------------- ### Run PHPUnit tests Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Executes the full test suite for the package using Composer. ```bash composer test ``` -------------------------------- ### Fluent Quota Consumption API Source: https://github.com/zaber-dev/laravel-quota/blob/main/LEARN.md Demonstrates the fluent interface for checking and consuming quotas. ```php Quota::for('action', $user)->limit(50)->perMonth()->consume() ``` -------------------------------- ### Registering Custom Storage Drivers Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Extend the QuotaManager within the AppServiceProvider to support custom storage backends like DynamoDB or MongoDB. ```php use ZaberDev\Quota\Contracts\QuotaDriverContract; use ZaberDev\Quota\Facades\Quota; public function boot(): void { Quota::extend('dynamodb', function ($app) { return new MyDynamoDbQuotaDriver($app['config']['quotas.drivers.dynamodb']); }); } ``` -------------------------------- ### Interact with Model Quotas Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Manage quotas directly from the model instance. ```php $user = User::find(1); // Consume 1 PDF export quota from the user's monthly budget $user->quota('pdf_exports')->limit(25)->perMonth()->consume(); // Check remaining budget $remaining = $user->quota('pdf_exports')->limit(25)->perMonth()->remaining(); ``` -------------------------------- ### Quota Facade Usage Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md The Quota facade provides a fluent interface to define limits, check usage, and consume quota units. ```APIDOC ## Quota::for($action, $target) ### Description Initializes a quota builder for a specific action and target entity. ### Methods - **limit(int $amount)**: Sets the maximum quota limit. - **perMinute() / perHour() / perDay() / perWeek() / perMonth() / perYear()**: Sets the time period for the quota. - **period($start, $end)**: Sets a custom time period. - **used()**: Returns the current usage count (int). - **remaining()**: Returns the remaining quota count (int). - **isExceeded()**: Returns true if the quota is exceeded (bool). - **hasCapacity(int $amount)**: Checks if there is enough capacity for the given amount (bool). - **consume(int $amount)**: Consumes quota units. Throws QuotaExceededException if insufficient capacity. - **enforce()**: Halts execution with a 429 error if the budget is exhausted. - **block(callable $callback, int $amount, int $lockSeconds)**: Executes a callback within an atomic lock and consumes quota upon success. - **reset()**: Resets the quota counter for the current period. - **flush()**: Removes all historical records for the action and target. ``` -------------------------------- ### Protecting Routes with Middleware Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Apply the CheckQuota middleware to routes to enforce usage limits based on specific keys, amounts, and time intervals. ```php use Illuminate\Support\Facades\Route; // Enforce a monthly allowance of 50 exports per User / IP address Route::post('/exports/generate', [ExportController::class, 'store']) ->middleware('quota:exports,50,month'); // Use a specific storage backend Route::post('/api/v1/query', [ApiController::class, 'query']) ->middleware('quota:api_query,1000,day,database'); ``` -------------------------------- ### Execute Atomic Blocks Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Use block() to ensure quota is only deducted if the callback completes successfully. ```php Quota::for('pdf_generation', $user) ->limit(50) ->perMonth() ->block(function () use ($pdfService, $user) { $pdfService->generate($user); }, amount: 1, lockSeconds: 30); ``` -------------------------------- ### Implement Success-Only Quota Middleware Source: https://github.com/zaber-dev/laravel-quota/blob/main/LEARN.md The handle method ensures quota units are only consumed when the request results in a 2xx or 3xx status code. ```php public function handle(Request $request, Closure $next, string $action, string $limit, string $period = 'day', ?string $driver = null): Response { $manager = app(QuotaManagerContract::class); $target = $request->user() ?? $request->ip(); $pending = $manager->for($action, $target)->limit((int) $limit); // 1. Configure period window and enforce existing limit before execution $this->applyPeriod($pending, $period); $pending->enforce(); // 2. Execute downstream controller inside try...finally $response = $next($request); // 3. ONLY consume quota units if request succeeded or redirected (HTTP 2xx or 3xx) if ($response->isSuccessful() || $response->isRedirection()) { $pending->consume(1); } return $this->addHeaders($response, $pending->info()); } ``` -------------------------------- ### Query Polymorphic Quotas Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Access the quotas relationship for database-backed storage. ```php // Get all database quota records assigned to this user $activeQuotas = $user->quotas()->where('period_end', '>', now())->get(); // Delete all quota records for this user $user->quotas()->delete(); ``` -------------------------------- ### Scheduling Database Pruning Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Automate the removal of expired quota records by scheduling the model:prune command in the Laravel console kernel. ```php use Illuminate\Support\Facades\Schedule; use ZaberDev\Quota\Models\Quota; Schedule::command('model:prune', ['--model' => Quota::class])->daily(); ``` -------------------------------- ### Reset or Flush Quotas Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Clear quota counters or historical records. ```php // Immediately reset the quota counter for the current period window Quota::for('api_queries', $user)->reset(); // Flush all historical quota records for this action and target Quota::for('api_queries', $user)->flush(); ``` -------------------------------- ### Enforce Quota Limits Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Halt execution if the quota is exceeded without consuming units. ```php Quota::for('api_queries', $user)->limit(1000)->perDay()->enforce(); ``` -------------------------------- ### Integrate Prunable in Quota Model Source: https://github.com/zaber-dev/laravel-quota/blob/main/LEARN.md Uses the Prunable trait to define cleanup logic for historical quota records based on period_end. ```php class Quota extends Model { use Prunable; public function prunable(): Builder { return static::query()->where('period_end', '<=', CarbonImmutable::now()); } } ``` -------------------------------- ### Eloquent Model Integration Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Using the HasQuotas trait to manage quotas directly on Eloquent models. ```APIDOC ## HasQuotas Trait ### Description Allows an Eloquent model to interact with quotas directly via the `quota()` method. ### Usage - **$model->quota($action)**: Returns a quota builder scoped to the model instance. - **$model->quotas()**: Accesses the underlying polymorphic relationship for database-backed quotas. ``` -------------------------------- ### QuotaInfo Data Transfer Object Source: https://github.com/zaber-dev/laravel-quota/blob/main/LEARN.md A strongly typed DTO used to return quota information, ensuring data integrity and providing helper methods for remaining capacity. ```php final class QuotaInfo { public function __construct( public readonly string $key, public readonly int $used, public readonly ?int $limit, public readonly CarbonImmutable $periodStart, public readonly CarbonImmutable $periodEnd, ) {} public function remaining(): int { if ($this->limit === null) { return PHP_INT_MAX; } return max(0, $this->limit - $this->used); } } ``` -------------------------------- ### Integrate HasQuotas Trait Source: https://github.com/zaber-dev/laravel-quota/blob/main/README.md Add the HasQuotas trait to your Eloquent models. ```php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use ZaberDev\Quota\HasQuotas; class User extends Authenticatable { use HasQuotas; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.