我正在使用 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'
];
}
我正在尝试在我的 Controller 中执行此操作
$validator = $request->validated();
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
但是 Flash 消息变成空的。 在使用 FormRequest
时设置 Flash 错误消息的最佳方法是什么?
我正在按照 View 模板设置我的 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 -->
最佳答案
FormRequest
自动执行,您不必在 Controller 中处理它。
它在
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',
...
];
}
要知道是否有错误,请检查 Blade 中的变量 $errors->default
然后您可以显示消息“表单未保存。检查下面的错误并重试"
关于laravel - 使用 FormResquest 时验证失败时的 Flash 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57971280/