Laravel includes a middleware to rate limit access to routes within your application. To get started, assign the throttle middleware to a route or a group of routes. The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes
For example, let's specify that an authenticated user may access the following group of routes 5 times per minute:
Route::group(['prefix' => 'api', 'middleware' => 'throttle:5'], function () {
Route::get('User_details', function () {
return User::all();
});
});
After implemented code in web.php pass url in chrome as below
http://localhost/laraveldemoproject/public/api/User_details
When you call method more than 5 times you receive Message as 429 | Too Many Requests
Dynamic Rate Limiting
You may specify a dynamic request maximum based on an attribute of the authenticated User
model. For example, if your User
model contains a rate_limit
attribute, you may pass the name of the attribute to the throttle
middleware so that it is used to calculate the maximum request count:
Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
Route::get('/user', function () {
//
});
});
Distinct Guest & Authenticated User Rate Limits
You may specify different rate limits for guest and authenticated users. For example, you may specify a maximum of 10
requests per minute for guests 60
for authenticated users:
Route::middleware('throttle:10|60,1')->group(function () {
//
});
You may also combine this functionality with dynamic rate limits. For example, if your User
model contains a rate_limit
attribute, you may pass the name of the attribute to the throttle
middleware so that it is used to calculate the maximum request count for authenticated users:
Route::middleware('auth:api', 'throttle:10|rate_limit,1')->group(function () {
Route::get('/user', function () {
//
});
});
Rate Limit Segments
Typically, you will probably specify one rate limit for your entire API. However, your application may require different rate limits for different segments of your API. If this is the case, you will need to pass a segment name as the third argument to the throttle
middleware:
Route::middleware('auth:api')->group(function () {
Route::middleware('throttle:60,1,default')->group(function () {
Route::get('/servers', function () {
//
});
});
Route::middleware('throttle:60,1,deletes')->group(function () {
Route::delete('/servers/{id}', function () {
//
});
});
});
To learn more about Routes Visit our Bajarangisoft site