简体   繁体   中英

API Throttle in Laravel 5.2

I was seeing this tutorial about throttle in Laravel 5.2

It seems that throttle is just used for APIs, but why couldn't be used for other controller stuff, to avoid that people send 100 times the same form through Postman.

I tell that, because in the Kernel.php, now, middleware are clearly divided between web and apis: Kernel.php:Laravel 5.2

You can apply it to web pages as well. Judging from your comments, you're confused as to the new features of Middleware, primarily Middleware Groups .

5.2 brought along with it a way to group Middleware like you would with Route groups before. In 5.1 you would do something like:

Route::group(['prefix' => 'api', 'middleware'=>'auth,custom_middleware,permission:edit_permissions'], function() {
    Route::post('permissions/{id}/store', ['uses'=>'PermissionController@store']);
});

That is still completely valid, but if you wanted to add another Route group with the same middleware, you had to either juggle organization so they were nested beneath a single Route group that applied those middleware or you had to copy paste the middleware, neither very desirable. With 5.2, all you have to is this:

Kernel.php

protected $middlewareGroups = [
    'permissions_api' => [
         'auth', 
         'custom_middleware',
         'permission:edit_permissions',
     ]
];

routes.php

Route::group(['middleware' => ['permissions_api']], function () {
    Route::post('permissions/{id}/store', ['uses'=>'PermissionController@store']);
});

Route::group(['middleware' => ['permissions_api']], function () {
    Route::post('permissions/{id}/update', ['uses'=>'PermissionController@update']);
});

So you can group those middleware and apply them in those groups. That's what the api and web you are seeing is. It's just the default Middleware groups provided by Laravel that you can modify however you want. throttle is available as Middleware where ever you may need it. The below are both perfectly valid

Route::group(['middleware' => ['throttle:60,1']], function () {
    Route::post('permissions/{id}/update', ['uses'=>'PermissionController@update']);
});

or

protected $middlewareGroups = [
    'permissions_api' => [
         'auth', 
         'custom_middleware',
         'permission:edit_permissions',
         'throttle:60,1'
     ] 
];

So throttle is just a middleware and can be applied just as any middleware is. It is defined in Kernel.php as 'throttle' => \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class, and the 60,1 are just middleware parameters, which were added in 5.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM