How to Validate an Array of Objects using validate in Laravel 8

October 27, 2021
Laravel
How to Validate an Array of Objects using validate in Laravel 8

In this post, you will learn how to validate the array of objects in laravel using validate function.

One of the common problems is that we need to validate the data other than a string type. In this tutorial, I will cover how to validate an array of objects in laravel.

Normal Validation:

Normally to validate the variable for example we do:

$validate = $request->validate([
    'title' => 'required',

]);

Array of object Validation:

To validate the array of objects, you need to use “*” for each item in an array and then “.” followed by the name of the object.

So let’s say we have an array of objects.

let json={
row:[
  {
   "title":"name",
   "post":"post name",
  },
  {
   "title":"name",
   "post":"post name",
  },
]
}

So we will validate it like following:

$validate = $request->validate([
    'row.*.title' => 'required',
    'row.*.post' => 'required',
]);

Both title and post are required in this case.

Also, read our article on validate phone number in laravel

Conclusion:

Hope you have learned today how to validate the array of objects using validate in laravel 8.

Let me know how it looks to you.

See you soon in another tutorial.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon