Laravel Usage Limiter - Manage Rate and Usage Limits


Introduction
Over the years, I've built many Laravel-powered SaaS applications. One of the core and common feature in almost any SaaS application is to manage usage consumption by users, accounts, or teams. The goal is to make sure users donโt overuse resources, whether itโs API calls, messaging limits, or anything else that requires control. Hence, I created a Laravel package that exactly does that --- Laravel Usage Limiter.
Laravel Usage Limiter helps you track and restrict how often users can use or consume a specific feature in your app over a period of time (e.g., limit API calls to 100 per day). By defining your own limits, you can start managing things like API request limits, message sending limits, or any other controlled usage features.
In this tutorial, Iโll walk you through how to install and use this package in your Laravel app, and weโll keep things super simple along the way. Letโs dive in!
Requirement
Laravel version 8.0 or higher.
Installation
Install Laravel Usage Limiter using the Composer package manager:
composer require nabilhassen/laravel-usage-limiter
Next, you should publish the Laravel Usage Limiter configuration and migration files using the vendor:publish Artisan command
php artisan vendor:publish --provider="NabilHassen\LaravelUsageLimiter\ServiceProvider"
Finally, you should run the migrate command in order to create the tables needed
php artisan migrate
Example Usage
So, let's assume we working on a Laravel-powered e-commerce application where suppliers can list and sell their products. Our application has two plans; Pro and Premium. Each of these plans have their own limits as described below.
- Pro: 20 Products
- Premium: 50 Products
So the first step will be to use the HasLimits
trait on the model that we would like to track which is likely the user model.
use NabilHassen\LaravelUsageLimiter\Traits\HasLimits; class User extends Authenticatable{ use HasLimits;}
Next, let's define our plans with their limits.
namespace Database\Seeders; use Illuminate\Database\Seeder;use NabilHassen\LaravelUsageLimiter\Models\Limit; class PlanSeeder extends Seeder{ /** * Run the database seeds. */ public function run(): void { // Pro plan can create 20 products Limit::create([ 'name' => 'products', 'allowed_amount' => 20, 'plan' => 'pro', 'reset_frequency' => 'every month', ]); // Premium plan can create 50 products Limit::create([ 'name' => 'products', 'allowed_amount' => 50, 'plan' => 'premium', 'reset_frequency' => 'every month', ]); }}
Once our seeder is ready, now we can run php artisan db:seed PlanSeeder
. Great!
In your User
creation logic, after a user is created, you should attach a limit to the user.
namespace App\Http\Controllers; class UserController{ public function store(Request $request) { $user = User::create($request->validated()); $user->setLimit('products', 'pro'); } public function destroy(User $user) { $user->unsetLimit('products', 'pro'); $user->delete(); }}
Now in our ProductController
class, whenever a supplier (i.e. the User) attempts to create a product, we can check their limits and decide if they're allowed to create more products or not meanwhile tracking their limits.
namespace App\Http\Controllers; class ProductController{ public function store(Request $request) { abort_if(! auth()->user()->hasEnoughtLimit('products'), 403); Product::create($request->validated()); auth()->user()->useLimit('products'); } public function destroy(Product $product) { $product->delete(); auth()->user()->unuseLimit('products'); }}
โ You're all set! Your application is now ready to track and manage resources and usage consumptions by your users.
Let's go one step further. At the beginning of this tutorial, when we defined our plans and limits, we have also set reset frequency for each of our limits as every month
.
Laravel Usage Limiter comes with built-in command line tools. We will utilize one of the available commands to automatically reset users limits based on the reset frequency we've set earlier.
// app/Console/Kernel.phpprotected function schedule(Schedule $schedule){ ... // Laravel <= 11 $schedule->command('limit:reset')->everyMinute(); // Laravel >= 10 $schedule->command('limit:reset')->everySecond(); ...}
๐๐ Your application is ready to manage, track, restrict, and automatically reset users limits.
More Features
What we've implemented to this point the regular implementation of the Laravel Usage Limiter package. There are more features provided by the package which you can explore by visiting the GitHub repo.
Conclusion
In summary, the Laravel Usage Limiter package is a powerful tool for any Laravel developer looking to implement usage restrictions in their applications. Whether you're building a SaaS product or a simple feature, this package allows you to easily track and manage user consumption while providing flexibility to define your own limits. By following the steps outlined in this tutorial, you can quickly integrate usage tracking into your app and ensure that users stay within their designated boundaries.
Don't forget to explore the additional features offered by the package on its GitHub repository. With the right configuration, you'll be well on your way to delivering a robust application that keeps resource management in check.
๐ป --- Happy coding!
Stay Updated.
I'll you email you as soon as new, fresh content is published.