繁体   English   中英

Laravel 5 如何显示像会话闪存这样的油门消息?

[英]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.

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