我正在将Laravel 5.5与FormRequest Validation一起使用。我当前的代码如下。这用于验证来自请求的数据。
如果可为空的字段在请求中的验证失败,则我希望请求继续,并将该字段的值设置为NULL。因此,例如,如果count
是作为字符串而不是整数发送的。我想将count的值设为NULL并继续进行请求。
是否可以使用此FormRequest?如果可以,怎么办?
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Response;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class FieldsCheck extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'userid' => 'required|integer',
'custom' => 'nullable|string|max:99',
'count' => 'nullable|integer'
];
}
protected function failedValidation(Validator $validator)
{
// if it fails validation, is there a way to change the failing value to null here and continue with the request?
}
}
答案 0 :(得分:0)
执行此操作的几个步骤。
$this->merge([$key => null])
将请求值覆盖为空。throw new HttpResponseException
发回验证错误。下面是一些带有注释的示例代码:
protected function failedValidation(Validator $validator)
{
$fields_to_null = ['count', 'custom']; // array of fields that should be changed to null if failed validation
foreach($validator->errors()->getMessages() as $key => $msg) {
// if fails validation && key exists in the array, change the field's value null and continue
if (in_array($key, $fields_to_null)) {
$this->merge([$key => null]);
} else {
// https://laracasts.com/discuss/channels/laravel/how-make-a-custom-formrequest-error-response-in-laravel-55?page=1
// if an error does not match a field in the array, return validation error
throw new HttpResponseException(response()->json($msg[0]),422);
}
}
}
该请求将继续发送到控制器,除非命中throw new httpResponseException