[英]Laravel 5 How to show throttle message like session flash?
我使用laravel 5.4,我想限制如下路線的請求
Route::group(['middleware' => ['throttle:2']], function () {
Route::post('/xxx', 'TestController@getTest');
});
它運行良好,但是當收到“Too Many Attempts”時。 它顯示在空白頁上。 有沒有辦法在刀片視圖中顯示這樣的會話 Flash 消息?
因此,一種簡單的方法是更改您的油門中間件。
首先,創建一個新的中間件來擴展基本油門中間件,如下所示:
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ThrottleRequests as
BaseThrottleRequests;
class ThrottleRequests extends BaseThrottleRequests
{
}
然后在 app/Http/Kernel.php 中更改您的油門中間件:
'throttle' => \App\Http\Middleware\ThrottleRequests::class
它現在將使用你自己的油門中間件,因為它是從 laravel 的中間件擴展而來的,它具有它的功能並且像以前一樣工作。
然后,查看基類內部,您會發現buildResponse
會在嘗試次數過多的情況下構建響應。 因此,您只需要在中間件中覆蓋它:
protected function buildResponse($key, $maxAttempts)
{
$retryAfter = $this->limiter->availableIn($key); // This gives you the number of seconds before the next time it is available
return redirect('test')->with('error', '...'); // You can use redirect() and all those stuffs as you would normally do to redirect the user and set a session message
}
創建一個中間件,例如 CustomThrottleRequests 在其中擴展 ThrottleRequests 中間件
覆蓋句柄方法
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
{
$key = $prefix.$this->resolveRequestSignature($request);
$maxAttempts = $this->resolveMaxAttempts($request, $maxAttempts);
if ($this->limiter->tooManyAttempts($key, $maxAttempts)) {
$retryAfter = $this->getTimeUntilNextRetry($key);
$retryAfter is in seconds
//here you can change response according to requirements
return redirect()->back()->withInput()->with('error','Too Many Attempts. Please try after '.$retryAfter .' seconds');
}
$this->limiter->hit($key, $decayMinutes * 60);
$response = $next($request);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}
現在在 app/Http/Kernel.php
change from
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
to
'throttle' => CustomThrottleRequests::class,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.