LiquidPL
LiquidPL

Reputation: 53

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.

Upvotes: 4

Views: 14928

Answers (2)

Diego Lima
Diego Lima

Reputation: 428

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'
]);

Upvotes: 12

ptvty
ptvty

Reputation: 5664

The unique validator keyword is for checking a value's duplicates in database.

You should use custom validator for such situations.

See: https://laravel.com/docs/5.1/validation#custom-validation-rules

Upvotes: 2

Related Questions