如何在Laravel 8中使用SweetAlert消息进行验证



我正在使用Laravel开发我的项目,当用户没有标记Recaptcha时,我想返回一条SweetAlert错误消息。我在LoginController.php:中对此进行了编码

use AppProvidersSweetAlertServiceProvider;
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
'g-recaptcha-response' => ['required' , new Recaptcha]
],[
'g-recaptcha-response.required' => alert()
->error('Bad','Attempt')->persistent('Ok')
]);
}

它不会显示警报,而是返回以下消息。

类UxWeb\SweetAlertNotifier的错误对象不能为转换为字符串

但是,我已经在提供程序部分的config/app.php中添加了此行。

UxWebSweetAlertSweetAlertServiceProvider::class

那么这里出了什么问题?我还应该做些什么来返回此警报消息?

您可以使用手动验证来返回字符串以外的内容:

$validator = Validator::make($request->all(), [
'username' => 'required|unique:posts|max:255',
'password' => 'required',
'g-recaptcha-response' => ['required' , new Recaptcha]
]);
if ($validator->fails()) {
if($validator->errors()->has('g-recaptcha-response'))
SweetAlert::error('please validate the captcha, thanks !')
return redirect()
->back()
->withErrors($validator)
->withInput();
}

还要确保你已经安装并在你的代码中包含了sweetalert:

安装:

composer require uxweb/sweet-alert

在您的控制器中:

use SweetAlert;

在您的刀片视图中:

<html lang="en">
<head>
<!-- Include this in your blade layout -->
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body>
@include('sweet::alert')
</body>
</html>

参考:

laravel文档(1(
uxweb/甜蜜警报回购(2(

最新更新