1
votes

I'm using Laravel 5.5 with FormRequest Validation. My current code is below. This is being used to validate the data form the request coming in.

If a nullable field fails validation in the request, I want the request to continue and make that field's value to NULL. So ,for example, if count is sent as a string instead of an integer.. I want to make the value of count NULL and continue with the request.

Is this possible using this FormRequest and if so, how?

<?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?
    }

}
1

1 Answers

0
votes

A couple of steps to do this.

  1. Have an array ready of the fields for which you want to change the value.
  2. Run a for each loop on the Validator to match the fields against the array you created in step 1.
  3. If the validation fails and matches the array, use $this->merge([$key => null]) to overwrite the request value to null.
  4. If validation fails and DOES NOT match the array, send back a validation error using the throw new HttpResponseException.

Here's some sample code below with comments:

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); 
        }
    }
}

The request will continue on to the controller unless it hits that throw new httpResponseException