我正在使用FormRequest进行验证。我试图通过Flash设置一个顶级错误消息,以向用户显示表单提交没有成功。
现在我有下面的UserResquest
class UserRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'first_name' => 'required|string|min:2|max:50',
'last_name' => 'required|string|min:2|max:50',
'date_of_birth' => 'required|date',
'gender' => 'required|in:male,female'
];
}我想在我的主计长身上做这件事
$validator = $request->validated();
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}但闪光灯的消息却是空的。使用FormRequest 时设置错误消息的最佳方法是什么?
我正在将我的Flash消息设置为以下视图模板。
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a></p>
@endif
@endforeach
</div> <!-- end .flash-message -->发布于 2019-09-17 09:31:24
FormRequest自动完成它,您不必在控制器中处理它。
它这样做
protected function failedValidation(Validator $validator)
{
throw (new ValidationException($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());
}如果需要其他行为,可以重载该方法。
要获取错误消息,需要在错误包中获取它。
{{ $errors->default->first('first_name') }}默认情况下,错误包名为default,可以在FormRequest扩展类中更改它。
自定义消息
若要设置每个错误的消息,请在UserRequest类中声明以下方法
public function messages()
{
return [
'first_name.required' => 'A first name is required',
'first_name.min' => 'The first name can\'t be a single character',
...
];
}要知道是否存在错误,请检查刀片中的变量$errors->default,然后可以显示消息“表单未保存。请检查下面的错误,然后再试一次”。
发布于 2019-09-17 13:46:08
正如N69S所指出的。我们可以在failedValidation下设置它,如下所示。
/**
* Handle a failed validation attempt.
*/
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
session()->flash('alert-danger', 'There was an error, Please try again!');
return parent::failedValidation($validator);
}https://stackoverflow.com/questions/57971280
复制相似问题