protected function validator(array $data)
{
$validation = Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed']
]);
if ($validation->fails())
{
return session()->flash('alert-danger', 'error');
}
}
protected function create(array $data)
{
$company = new Company();
$company->store_name = $data['company_name'];
$company->save();
}
检查验证器功能内部的故障状态,并显示错误消息
request()->validate([
'email' => 'required'
],
[
'email.required' => 'You have to choose the email!',
]);
尝试下面的代码,而不是上面的验证
request()->validate([
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
];
现在,如果你删除代码
if ($validation->fails())
{
return session()->flash('alert-danger', 'error');
}
代码将在没有任何错误的情况下运行。如果您没有在输入字段中输入任何值请求->validate((将检查所有请求。
您需要在if ($validation->fails())
检查中实际返回一些内容。现在,您正在设置会话Flash,但返回null
(->flash()
没有返回值(。
这里有几个解决方案,但这取决于这是表单提交还是AJAX请求:
protected function validator(array $data) {
return Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed']
]);
}
protected function create(array $data) {
$validator = $this->validator($data);
if ($validator->fails()) {
session()->flash('alert-danger', 'error');
// If this is an AJAX Request:
if (request()->ajax()) {
return response()->json(['errors' => $validator->errors()], 422);
}
// If this is a Form Submission:
return back()->withErrors($validator->errors());
}
$company = new Company();
$company->store_name = $data['company_name'];
$company->save();
}
基本上,修改validator
方法以返回Validator::make()
实例,在create()
方法中检查它,并根据这是AJAX请求还是表单提交来适当地返回。