Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a JSON array in Laravel

I have a controller which receives a following POST request:

{
  "_token": "csrf token omitted",
  "order": [1,2,3,4,5,6,7,8]
}

How can I use validators to ensure that elements in order are unique, and between 1 and 7? I have tried the following:

$this->validate($request, [
    'order' => 'required|array',
    'order.*' => 'unique|integer|between:1,7'
]);

The first clause is checked, the secound one passes even when the input is invalid.

like image 694
LiquidPL Avatar asked Oct 18 '25 15:10

LiquidPL


1 Answers

Using distinct rule:

distinct

When working with arrays, the field under validation must not have any duplicate values.

In your case, it could look like this:

$this->validate($request, [
    'order' => 'required|array',
    'order.*' => 'distinct|integer|between:1,7'
]);
like image 171
Diego Lima Avatar answered Oct 20 '25 05:10

Diego Lima