Toastr通知失败表单提交
问题描述:
我在我的应用程序中使用toastr通知。当表单提交由于验证失败或表单提交成功时,我会发送通知。我通常做这种方式:Toastr通知失败表单提交
public function store(Request $request) {
$data = $request->all();
$rules = [
'name' => 'required|string',
'email' => 'required|email',
'message' => 'required|string',
'g-recaptcha-response' => 'required|captcha',
];
$validate = Validator::make($data, $rules);
if ($validate->fails()) {
$error = array(
'message' => "Error sending the message!",
'alert-type' => 'error'
);
return back()->withErrors($validate)->withInput()->with($error);
}
Feedback::create($data);
$success = array(
'message' => "Thanks for the feedback! Your message was sent successfully!",
'alert-type' => 'success'
);
return redirect()->route('contactus')->with($success);
}
但是当表中的列数大(10列或更多),我想使用表单请求类代替,而不是在店里方法声明的规则。因此,它成了这个样子:
public function store(FeedbackRequest $request) {
$data = $request->all();
Feedback::create($data);
$success = array(
'message' => "Thanks for the feedback! Your message was sent successfully!",
'alert-type' => 'success'
);
return redirect()->route('contactus')->with($success);
}
的问题是,使用表单请求时,我不知道如何在验证失败时发送错误通知。有没有办法检查表单请求类验证是否失败,以便我可以发送错误通知?这一切,并感谢!
答
Adding After Hooks To Form Requests正是你需要在你的请求类的内容:
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($validator->failed()) {
$validator->errors()->add('field', 'Something is wrong with this field!'); // handle your new error message here
}
});
}
也做到了,我需要更经常地阅读文档。谢谢 –