Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How To Set Rate Limit On Routes In Laravel

How To Set Rate Limit On Routes In Laravel?

In this tutorial, I will give you an example of “How To Set Custom Rate Limit On Routes in Laravel”, so you can easily apply it to your Laravel 5, Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10 applications.

First, what we’re doing here, This is the example :

How To Set Custom Rate Limit On Routes in Laravel

How to implement Rate Limiting in Laravel

Rate Limit On Routes In Laravel

In Laravel, rate limiting is a way to control the number of requests that a user or IP address can make to a particular route or group of routes within a specified time period. This helps prevent abuse and ensures fair usage of your application’s resources.

To implement rate limiting in Laravel, you can use the built-in rate limiting middleware. Here’s a basic example of how to set up custom rate limiting on a route:

Configure Rate Limiting:

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        #Create a custom rate limiter
        RateLimiter::for('custom_limit', function(Request $request){
            return Limit::perMinute(4);
        });
    }
}

The ThrottleRequests middleware is responsible for handling rate limiting.

Apply Rate Limiting to a Route:

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('/example',function() {
    return "This is an example of Rate Limit in Laravel";
    })->middleware('throttle:custom_limit');

You can customize these configurations based on your specific needs. Laravel’s rate limiting provides flexibility in terms of setting limits, adjusting response formats for exceeded limits, and more.

Route::middleware('throttle:custom_limit')->group(function () {


    // Your route definitions go here


});

Keep in mind that the specifics might vary based on the Laravel version you are using, so always refer to the official documentation for the version you are working with.

I hope that this article helped you learn  How To Set Custom Rate Limit On Routes in Laravel. You may also want to check out our guide on How to set Limit on Login Attempt in Laravel.