Original address :https://www.wjcms.net/archives/laravel8 Update rate limit improvement
Laravel The request rate limiter for has been enhanced , More flexibility and functionality , At the same time, it remains the same as the previous version of throttle middleware API Backward compatibility .
The rate limiter is used RateLimiter Facade for Method defined . The for Method accepts a rate limiter name and a Closure, The Closure Returns the limit configuration that should be applied to the route to which the rate limiter is assigned :
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('global', function (Request $request) {
return Limit::perMinute(1000);
});
Since the rate limiter callback receives the incoming HTTP Request instance , So you can dynamically build appropriate rate limits based on incoming requests or authenticated users :
RateLimiter::for('uploads', function (Request $request) {
return $request->user()->vipCustomer()
? Limit::none()
: Limit::perMinute(100);
});
Sometimes you may want to subdivide the rate limit by any value . for example , You may want to allow users to each IP Address every minute 100 Access to the given route . So , You can by Use the following method when establishing the rate limit :
RateLimiter::for('uploads', function (Request $request) {
return $request->user()->vipCustomer()
? Limit::none()
: Limit::perMinute(100)->by($request->ip());
});
have access to throttle Middleware attaches a rate limiter to a route or routing group . The throttle middleware accepts the name of the rate limiter that you want to assign to the route :
Route::middleware(['throttle:uploads'])->group(function () {
Route::post('/audio', function () {
//
});
Route::post('/video', function () {
//
});
});