前端部分
正在像这样发送参数:
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的东西。
答案 0 :(得分: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验证的数组。
答案 1 :(得分:1)
您应该能够像这样在您的请求中覆盖validationData方法:
protected function validationData()
{
$this->merge(['car', json_decode($this->car)]); // or what ever your request value is.
return $this->all();
}