【问题标题】:Validate Parameters as a JSON String in Laravel在 Laravel 中将参数验证为 JSON 字符串
【发布时间】:2019-05-05 07:30:52
【问题描述】:

前端部分

参数是这样发送的:

Laravel 请求

class CarCreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        //TODO: Define authorization logic, possibly a middleware
        return true;
    }  

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'car.name' => 'present|required'
        ];
    }
}

真正的问题

请求类始终验证为 false。我检查了Validating Array 部分,但它看起来像这样发送参数:

car[name]=Spidey Mobile

但是,我需要使用 JSON.stringify() 将这些数据字符串化。

有解决办法吗?看起来点表示法不起作用,因为这是一个 JSON 字符串而不是数组。我尝试在评估之前修改请求数据,但我没有找到适用于 Laravel 5.7 的任何内容。

【问题讨论】:

  • 在评估之前您是如何修改请求数据的?那将是你最好的选择。 json_decode您的请求并设置为验证数据。
  • car: {"name": "Spidey Mobile"} 似乎不是有效的 json 格式。 {"car": {"name": "Spidey Mobile"}} 是。
  • 附带说明,您不需要在验证中使用presentrequired,因为仅required 将检查该字段是否存在,以及它是否不为空。
  • @CUGreen 我在 ValidationData 方法中使用了 json_decode,但它看起来不再适用于 5.7。它根本没有改变任何东西

标签: php json laravel laravel-5 laravel-validation


【解决方案1】:

这是解决方案,我在请求中同时使用了 sanitize 和 validator 方法,以便在评估之前更改请求数据。

class CarCreateRequest extends FormRequest
{
    /**
    * Determine if the user is authorized to make this request.
    *
    * @return bool
    */
    public function authorize()
    {
        //TODO: Define authorization logic, possibly a middleware
        return true;
    }  

    public function validator($factory)
    {
    return $factory->make(
        $this->sanitize(), $this->container->call([$this, 'rules']), $this->messages()
    );
    }

    public function sanitize()
    {
        $this->merge([
            'car' => json_decode($this->input('car'), true)
        ]);
        return $this->all();
    }

    /**
    * Get the validation rules that apply to the request.
    *
    * @return array
    */
    public function rules()
    {
        return [
            'car.name' => 'present|required'
        ];
    }
}

json_decode 会将 JSON 字符串转换为 Laravel 可以验证的数组。

【讨论】:

    【解决方案2】:

    您应该能够像这样覆盖您的请求中的validationData 方法:

    protected function validationData()
    {
        $this->merge(['car', json_decode($this->car)]); // or what ever your request value is.
        return $this->all();
    }
    

    【讨论】:

    • 我确定这种方法是有原因的?您确定在控制器存储方法中将您的请求投射到CarCreateRequest 吗?在validationData() 中尝试和dd($this->all()); 以确保它通过并返回正确的数据。
    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2012-07-02
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多