Search code examples
laravelvalidationlaravel-5laravel-validation

How to validate and insert array of objects in php?


I want to validate and insert array of object into my database. This is my array of objects: (Front end js)

studentData: [
  {id: 1, name: 'Juan'},
  {id: 2, name: 'Jema'},
]

This is my current code for StudentController.php:

for($i; $i <= count($request->input());  $i++){
  $student = Student::create([
    'id' => $request[$i]["id"],
    'name' => $request[$i]["name"],
  ]);
}

and this works perfectly when I'm inserting all my object. Now, I want to validate all the request. This code is not working:

$validate = $request[$i]->validate([
                'id' => 'required|unique:students|numeric'
            ]);

for($i; $i <= count($request->input());  $i++){
  $validate = $request[$i]->validate([
    'id' => 'required|unique:students|numeric'
  ]); //this is the error. I cant validate the data foreach user

  $student = Student::create([
    'id' => $request[$i]["id"],
    'name' => $request[$i]["name"],
  ]);
}


Solution

  • You have to do array input validation with dot like this:

    $this->validate($request,[
        'studentData.*.id' => 'required|unique:students|numeric',
        'studentData.*.name' =>'required'
    ],
    $messages = [
     // write error messages
    ]);
    

    I hope you will understand.

    You can see laravel docs for array input validation here https://laravel.com/docs/5.6/validation#validating-arrays