[Laravel 5.4] Web Route Throttle

Laravel 預設的 throttle middleware 只有在 api 的 route 有統一加上,如果 web route 想用的話也可以自行加入。

例如:10 分鐘只能連線 5 次
全部的 web route 都加。
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'throttle:5,10',
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];
特定的 route group 才加。
Route::group(['middleware' => 'throttle:5,10'], function () {
    Route::get('/testThrottle', function () {
        return 'ok';
    })->middleware('throttle:5,10');
});
特定的 route 才加。
Route::get('/testThrottle', function () {
    return 'ok';
})->middleware('throttle:5,10');
成功會回傳 ok;失敗會回傳 Too Many Attempts. 錯誤代碼 429。

不過我測試下來發現,他好像一定會噴這個字串,做一個 429 的 error view 也沒啥作用。所以如果想要自訂文案和畫面的話可能要另外寫一個 class 去繼承 ThrottleRequests,並改寫 buildResponse 方法,然後把 web route 改成新的,不過這部分我就沒測了。

留言