13

Laravel 8 Rate Limiting per IP address

 2 years ago
source link: https://www.laravelcode.com/post/laravel-8-rate-limiting-per-ip-address
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Laravel 8 Rate Limiting per IP address

  6608 views

  8 months ago

Laravel

Laravel provides variety of custom rate limiter services out of the box which allows you to restrict the traffic to given routes. To use Laravel's rate limiter service, you need to set rate limiter.

In this article, we will discuss on how you can set number of request per IP address to specific routes. So let's start working on code.

First of all open App\Providers\RouteServiceProvider class and add configureRateLimiting method in it.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('global', function (Request $request) {
            return Limit::perMinute(10)->by($request->ip());
        });
    }
}

RateLimiter facade's for method accepts two parameters. First one defines the name of limit and second closure that returns limit configuration which will apply on route. Illuminate\Cache\RateLimiting\Limit class instance will define Limit configuration.

By default, after limit exceeds, application will return response with a 429 HTTP status code. If you want to send custom response, you can chain response method.

RateLimiter::for('ip_address', function (Request $request) {
    return Limit::perMinute(10)->by($request->ip())->response(function() {
        return response('Your return message', 429);
    });
});

After you define rate limit in AppServiceProvider, now you need to attach with routes or route group using throttle middleware. Open routes/web.php file and add groups around the routes which you want to limit.

<?php

use App\Http\Controllers\VideoController;

Route::middleware(['throttle:ip_address'])->group(function () {
    Route::get('/video-view', [VideoController::class, 'videoView']);
});

That's it now every request for these routes will limited to 10 requests per ip address.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK