我在我的应用中使用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列或更多)时,我想使用表单请求类而不是在store方法中声明规则。所以它变成了这样:
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);
}
问题是,当使用表单请求时,我不知道如何在验证失败时发送错误通知。有没有办法检查表单请求类验证是否失败,以便我可以发送错误通知?这就是全部,谢谢!
答案 0 :(得分:0)
Adding After Hooks To Form Requests正是您在Request类中所需要的:
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
}
});
}