Search code examples
laravelvalidationrequest

Laravel validation timesout for huge data


I have laravel FormRequest which prepares rules for validation. I have dumped prepareForValidation function at the end and it shows dump immediately, but when I try to call $request->validation() function in controller it takes too long. I have validations like required|numeric|max:999999.99|min:0|email. When I send 1000 items which holds for each item almost 45 fields.

There is not any actions before this validation from my code side. Is there any solution to handle this kind of things? Requests sends via API.


Solution

  • Laravel validation is slow with large arrays. I have sent an issue and PR to Laravel for fixing it. My PR was not accepted. What you can do now before fixing Laravel:

    1. For array validation, separate validating array size with validating items. This makes sure when users send you large arrays, your servers CPU doesn't get wasted:
    $request->validate(['array' => 'required|array|max:100']);
    $request->validate(['array.*' => 'required|numeric|max:1000']);
    
    1. If possible design your API to not take large arrays. It is not a best practice to accept large arrays after all, regardless of validation speed. Don't accept arrays of size 10,000. If user needs to send 10,000 records to your server, maybe they should send them via 100 requests each holding 100 records.
    2. You also can validate your data in chunks of smaller size to boost the performance.
    collect($request['array'])->chunk(100)->each(function (array $chunk) {
        Validator::validate(
            ['array' => $chunk],
            ['array.*' => 'required|numeric|max:1000']); 
    });
    
    1. You always have option to validate the input by means other than Laravel validation. It may be simpler than you think.