首页 > 解决方案 > 使用 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)调用数组上的成员函数失败()

标签: laravellaravel-form

解决方案


使用表单请求类

如果验证失败,将自动生成重定向响应以将用户发送回之前的位置。错误也将闪现到会话中,以便显示。如果请求是 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');
}

推荐阅读