Search code examples
laravel-5laravel-validation

Validation of array in FormRequest in Laravel 5


I use Ajax to send form data to a resource controller (Laravel 5). However I send my form fields with this call as an Array (no direct form field vars)

I have setup a Request with the rules which need to be validated.

However the default behaviour of this kind of validation is that it only looks at the direct field variables inside the Request object. So for instance if I would send: input name="firstname", I simply would have to set

public function rules()
{
    return [
        'firstname' => 'required|alpha|between:1,128'
    ];
}

But now, how can I validate an array inside the Request object? So for instance, what if I would send input name="nameArray['firstname']"?

So what I want to do is to modify the Request object before it is sent to the validation. Or maybe there is a better way to deal with this. I know one can loop through the object inside the rules method like this:

 foreach($this->request->get('nameArray') as $key => $val)
 {

 }

But that doesn't help, as the Validator of Laravel will use the direct fields set in the Request object. So I can't change that here. I want to get the individual form fields out of the array, and put them back directly in the Request object, so Validation can be done with the same way of setting the rules etc.

Btw, I use this method of Validation, by calling the Request method inside the resource controller where, in this example, I want to store the input.

public function store(CreateStudentRequest $request)
{
}

Solution

  • I would create a middleware for sanitizing the request object.

    class SanitizeMiddleware
    {
        /**
         * Run the request filter.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // here do the sanitation needed to 
            // make the request object work with the validator
        }
    
    }
    

    I would probably create the sanitation methods on its own class and just inject it through the controller to keep the code clean.

    Also you can also do the sanitation in the Javascript side if that's easier for you.