Laravel Throttle限流提示如何将:seconds单位改为小时显示?
实现方案
你可以通过重写Laravel原生限流中间件+修改语言配置的方式实现,步骤如下:
步骤1:修改认证语言配置
打开 resources/lang/en/auth.php,调整throttle的提示文本:
// 如果你需要适配单复数显示可以用复数规则,也可以直接写死hour(s) 'throttle' => 'Too many login attempts. Please try again in :hours hour.|Too many login attempts. Please try again in :hours hours.', // 简单写法直接用 'throttle' => 'Too many login attempts. Please try again in :hours hour(s).' 也可以
步骤2:自定义限流中间件
运行命令生成自定义中间件,覆盖原生限流的返回逻辑:
php artisan make:middleware CustomThrottleRequests
打开生成的 app/Http/Middleware/CustomThrottleRequests.php 文件,写入以下内容:
<?php namespace App\Http\Middleware; use Illuminate\Routing\Middleware\ThrottleRequests as BaseThrottleRequests; use Illuminate\Validation\ValidationException; class CustomThrottleRequests extends BaseThrottleRequests { protected function buildException($key, $maxAttempts) { $retryAfter = $this->getTimeUntilNextRetry($key); // 秒转小时,向上取整,不足1小时按1小时计算 $retryHours = (int)ceil($retryAfter / 3600); return ValidationException::withMessages([ 'email' => [trans('auth.throttle', ['hours' => $retryHours])], ])->status(429) ->header('Retry-After', $retryAfter) ->header('X-RateLimit-Remaining', 0) ->header('X-RateLimit-Reset', time() + $retryAfter); } }
步骤3:替换内核中间件绑定
打开 app/Http/Kernel.php,找到$routeMiddleware数组,将原生的throttle中间件替换为你自定义的类:
protected $routeMiddleware = [ // 其他中间件保持不变 'throttle' => \App\Http\Middleware\CustomThrottleRequests::class, ];
额外说明
如果你需要调整限流的总时长本身(比如从默认15分钟改成2小时),直接修改路由中throttle中间件的参数即可,比如throttle:5,120代表120分钟内最多允许5次登录尝试。
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

