Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validate array of objects

Tags:

laravel

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?

like image 848
user2722667 Avatar asked Jan 18 '18 17:01

user2722667


People also ask

How to validate object array in Laravel?

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.

How do you validate exact words in laravel?

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.


2 Answers

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

like image 63
Mauricio Rodrigues Avatar answered Oct 29 '22 22:10

Mauricio Rodrigues


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.

like image 26
Michael Aaron Wilson Avatar answered Oct 29 '22 23:10

Michael Aaron Wilson