我在 LoginController 中添加了一项检查来限制用户连接设备的最大数量。
我在 LoginController 的 login() 方法中添加了以下内容:
public function login(Request $request)
{
// ... some code ...
if ($this->attemptLogin($request)) {
$user = Auth::user();
if ($user->max_devices >= 5) {
// if I dd() instead of returning this, it gets here
return $this->sendMaxConnectedDevicesResponse($request);
}
}
// ... some code ...
}
protected function sendMaxConnectedDevicesResponse(Request $request)
{
throw ValidationException::withMessage([$this->username() => ['Device limit reached'])->status(403);
}
sendMaxConnectedDevicesResponse 是带有我的自定义消息的 sendLockoutResponse 的副本,但是我收到警告,提示我有未处理的异常 (Unhandled \Illuminate\Validation\ValidationException< /代码>)。
那么我该如何像 sendLockoutResponse 处理它一样处理它,这样它就会在前端显示为错误,而不是仅仅忽略它?现在,发生的情况是,即使它抛出错误,它也不会在前端显示它,并且继续照常登录
我只是没有找到正确抛出和捕获自定义错误的方法
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在我的一个项目中,我使用了这个
throw ValidationException::withMessages([ 'key' => 'error message', ]);在你的中,你可以使用
throw ValidationException::withMessages([ 'device_limit' => 'Device limit reached', ]);因此,在前端,您可以使用
device_limit 键获取错误。在您的登录控制器中
use Illuminate\Http\Request; use Illuminate\Http\Exceptions\HttpResponseException; class LoginController extends Controller { use AuthenticatesUsers; protected function authenticated(Request $request, $user) { if ($user->max_devices >= 5) { // Logout the user right after login $this->guard()->logout(); // Throw an instance of HttpResponseException throw new HttpResponseException( response()->json(['error' => 'Device limit reached'], 403) ); } } }