1

I would like to handle POST requests with an array of objects in their body as follows:

[
  {"path":"./../../", ...},
  {"path":"./../../", ...},
  {"path":"./../../", ...},
  ...
]

I haven't found any way to set a validation rule that will limit the max length of such an array, that is located in the root of the POST request body, for example up to 100 objects.

The only related solution I see here is to limit the PHP POST size via post_max_size option, however, it's not what I am looking for. Does anyone know how to set a proper validation rule for this case?

I'm using Laravel8.

Prisacari Dmitrii
  • 1,985
  • 1
  • 23
  • 33
  • Wrong way round, leave `post_max_size` alone. Stuff in the POST is controlled by what you place in your form or how you build the data for an ajax call. _I am tempted to say, if you dont build it, they wont come_ – RiggsFolly Jan 06 '21 at 14:21
  • 1
    You can use `"arr_param" => ["required","array","min:2","max:4"], // validate an array contains minimum 2 elements and maximum 4` – Derek Pollard Jan 06 '21 at 14:22
  • 1
    @DerekPollard But that does not stop 1000 occurances being sent though does it. I thought that was what the question was about – RiggsFolly Jan 06 '21 at 14:42
  • @RiggsFolly Exactly! – Prisacari Dmitrii Jan 06 '21 at 14:43

2 Answers2

1

To extend a bit on the answer already given by Derek, you can just use the laravel validator to validate your request. This validator also contains the min and max size options.

For more info see https://laravel.com/docs/8.x/validation#available-validation-rules

4Fingers
  • 89
  • 6
0

You can define your custom rule in laravel:

1- First Create a custom rule with artisan command:

php artisan make:rule ArrayCheck

2- Go to app/Rules folder and Edit ArrayCheck.php:

<?php

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;

class ArrayCheck implements Rule {
    
    public function passes($attribute, $value) {
        return count($value) <= 10;
    }

    
    public function message() {
        return 'Your Array is bigger than our limits!';
    }
}

3- Then you can use your custom rule every where you want:

use App\Rules\ArrayCheck;

$request->validate([
    'hobbies' => ['required', new ArrayCheck],
]);
Dharman
  • 30,962
  • 25
  • 85
  • 135