darius92's avatar

Request rules validation is very slow

My request have array of ~2000 items.

I want to use validation rules, but its super slow.

class MyItemsRequest extends FormRequest {
    public function rules() {
        return [
            'items' => 'required|array',
            'items.*.id' => 'required|integer',
            'items.*.meta_data' => 'required|string',
            'items.*.stuff' => 'sometimes|nullable|integer',
            'items.*.more_stuff' => 'required',
        ];
    }
}

Each line of 'items.*.xx' => 'xx' add's 3sec to request. So this request takes at least 12 sec just to check rules.

For testing purpose I tried multiple validation loops like this in controller just to check loop performance:

foreach ($request->get('items') as $item){
      is_int($item['id']);
}

and writing even 5 loops does not decrease performance so bad like rules validation.

Why it's so slow? I'm using wrong?

1 like
4 replies
36864's avatar
36864
Best Answer
Level 13

There's quite a lot of overhead in the validator class. For small datasets (i.e: the majority of use cases) this is negligible, but it does scale with the number of items to validate.

For large dataset validation you're better off doing it manually instead of using the validator.

2 likes
ejdelmonico's avatar

I would just inject the form request into the controller method like MyItemsRequest $request and then just use $validated = $request->validated(). Do whatever with the input like save it. It should redirect if not valid and will only try to validate the input you designate to be validated in the request class.

2 likes
vincent15000's avatar

Can you show where / how you use this form request please ?

Have you tried to minimize your array with only one item to check if this only item needs also 3 seconds to be validated ?

Please or to participate in this conversation.