如何解决Laravel7 - 检测到节流时重定向到特定视图
在登录期间检测到限制时,我需要将用户重定向到一个简单的信息视图。
我有一个名为 suspended.blade.php
的视图我已经设置了路线
Route::get('/suspended',function(){
return view('suspended');
});
我正在使用 Cartalyst/Sentinel。
在我的登录控制器中,我有这样的东西:
function LoginUser(Request $request){
// some validation stuff...
try {
$user = Sentinel::authenticate($request->all());
} catch (ThrottlingException $e) {
// user inserted too many times a wrong password
return redirect('/suspended');
} catch (NotActivatedgException $e) {
return redirect()->back()->with( ['error' => "Account not active yet."] );
}
// some other stuff...
}
如果我模拟小跑,我只会得到一个错误页面,而不是我的视图。
这是为什么?
谢谢
编辑 按照@PsyLogic 的提示,我像这样修改了我的函数:
function LoginUser(Request $request){
// some validation stuff...
try {
$user = Sentinel::authenticate($request->all());
}
/* remove this part to use the default behaviour described in app\Excpetions\Handler.php */
// catch (ThrottlingException $e) {
// return redirect('/suspended');
// }
catch (NotActivatedgException $e) {
return redirect()->back()->with( ['error' => "Account not active yet."]
);
}
// some other stuff...
}
仍然不起作用,并显示包含所有调试代码的 Laravel 错误页面。
解决方法
Laravel 已经有节流中间件,你可以扩展它并更新 handle()
方法
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ThrottleRequests;
class CustomThrottleMiddleware extends ThrottleRequests
{
//...
}
并更新您的 Handle.php 文件中的新中间件
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,// ...
'throttle' =>App\Http\Middleware\CustomThrottleMiddleware::class,]
或者您可以保留原始索引限制并添加您的 s
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,// ...
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,'custom_throttle' =>App\Http\Middleware\CustomThrottleMiddleware::class,]
更新(简单的方法)
事件这些更改不会影响您的包,但让我们用简单的方法来做,您可以更新 render()
中的 App\Exceptions\Handler::class
函数并进行测试
public function render($request,Throwable $exception)
{
if ($exception instanceof ThrottleRequestsException) {
return redirect()->route('suspended');
}
return parent::render($request,$exception);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。