user3573738
user3573738

Reputation:

How to write validation rule for JSON laravel?

There is JSON object that I want to validate:

[{
  "id": 1,
  "settings": {
    "GRSYSEM": 1
  }
},
{
  "id": 2,
  "settings": {
    "GRSYSEM": 1
  }
},
{
  "id": 3,
  "settings": {
    "GRSYSEM": 1
  }
}
]

How to write validation rule in Laravel?

I tried this rule:

$validator = Validator::make($request->all(), [
    'id' => 'required|array',
    'id.*' => 'required',
    'settings.*.GRSYSEM' => 'required'
]);

Upvotes: 2

Views: 107

Answers (2)

bjovanov
bjovanov

Reputation: 481

If entry in $request->all() is id (as I can see), you should try like that :

$validator = Validator::make($request->all(), [
    'id' => 'required|array',
    'id.*.id' => 'required',
    'id.*.settings.GRSYSEM' => 'required'
]);

Upvotes: 0

Namoshek
Namoshek

Reputation: 6544

You are almost there, simply put the wildcard * first:

$validator = Validator::make($request->all(), [
    '*.id' => 'required',
    '*.settings.GRSYSEM' => 'required'
]);

It literally says: For each element in the array, I expect an id and a setting GRSYSEM.

You could also ensure it's an array by using a little hack:

$data = ['input' => $request->all()];

$validator = Validator::make($data, [
    'input' => 'required|array',
    'input.*.id' => 'required',
    'input.*.settings.GRSYSEM' => 'required'
]);

Upvotes: 2

Related Questions