I wonder if its possible to validate a array of objects in Laravel? I have built a form looking like a excell page using vue, so the user can edit many rows that later gets uploaded.
The data that I wish to validate when posting to my controller looks like this:
rows[
0 {
title: "my title",
post: "my post text"
},
1 {
title: "my title",
post: "my post text"
},
2 {
title: "my title",
post: "my post text"
}
]
So for example how can I add a required rule to each input?
To validate an array of objects in Laravel, you can use the * identifier for each item in an array, and use the “.” syntax to point to the property. $validated = $request->validate([ 'row. *. title' => 'required', 'row.
To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.
You can use array validation of Laravel.
eg.
$validator = Validator::make($request->all(), [
'row.*.title' => 'required',
'row.*.post' => 'required',
]);
You can find more about Laravel array validation here
The approved answer works if your posting an array, however to take it a step further, I am needing to save multiple arrays. While that approach would work if I make two separate endpoints, what if I want to save everything inside one DB::transaction
?
Viola:
// POST:
{
"array1": [
{ "key1": "string", "key2": 1 },
{ "key1": "string", "key2": 0 }
],
"array2": [
{ "key3": "string", "key4": 1 },
{ "key3": "string", "key4": 0 }
]
}
// SERVER:
$this->validate($request, [
'array1' => 'present|array',
'array2' => 'present|array',
'array1.*.key1' => 'required|string',
'array1.*.key2' => 'required|integer',
'array2.*.key3' => 'required|string',
'array2.*.key4' => 'required|integer'
]);
DB::transaction(function() use($request) {
foreach($request['array1'] as $x){
// ...do stuff here
};
});
Note: 'present|array'
accepts empty arrays whereas 'required|array'
would reject them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With