laravel - 使用 laravel 请求类时,在数组错误上调用成员函数失败()
问题描述
我正在使用自定义请求类进行 laravel 表单验证。
这是我的请求类
class ContactUsRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'lname' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'lname.required' => 'please enter the last name'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
这就是我所说的,
public function send(ContactUsRequest $request) {
$validator = $request->validated();
if ($validator->fails()) {
return redirect('/contactus')
->withErrors($validator)
->withInput();
} else {
ContactUs::create($request->all());
return redirect('/contactus');
}
}
但是当我输入正确的值时,我得到了这个,
Symfony \ Component \ Debug \ Exception \ FatalThrowableError(E_ERROR)调用数组上的成员函数失败()
解决方案
使用表单请求类
如果验证失败,将自动生成重定向响应以将用户发送回之前的位置。错误也将闪现到会话中,以便显示。如果请求是 AJAX 请求,将向用户返回带有 422 状态代码的 HTTP 响应,其中包括验证错误的 JSON 表示。
为了捕获验证失败,您可以使用Validator门面
例如
use Illuminate\Support\Facades\Validator;
//...
public function send(Request $request) {
$validator = Validator::make($request->all(), [
'lname' => 'required'
// ...
]);
if ($validator->fails()) {
return redirect('/contactus')
->withErrors($validator)
->withInput();
}
ContactUs::create($request->all());
return redirect('/contactus');
}
我们可以像这样保持ContactUsRequest。
public function send(ContactUsRequest $request) {
$validator = $request->validated();
ContactUs::create($request->all());
return redirect('/contactus');
}
推荐阅读
- javascript - 如果在字符串中找到,javascript保存单词
- openssl - 使用 Openssl 验证签名文档
- python - 无法在 python 和 selenium 自动化中传递价值
- javascript - 错误:ENOENT:没有这样的文件或目录,访问
- telethon - 如何修复 InvalidPeer 错误(Teleton ReportRequest)?
- sql - 当 SAL col 更新为新的加薪时触发火灾。此外,触发器将更新 EMPL 表中 X 列中 20% 的加薪金额
- mongodb - 如何在聚合中合并文档中的数组?
- mysql - 如何为表的所有列添加空值
- javascript - 连接两个 tf.data.Dataset 在 tensorflow.js 中给出“this.lastRead.then 不是函数”错误
- jupyter-notebook - 酒店订购菜单的 Python 代码未按预期运行 (LOOPS)