How to validate array of objects in laravel?

Member

by orpha , in category: PHP Frameworks , 3 months ago

How to validate array of objects in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 3 months ago

@orpha 

In Laravel, you can validate an array of objects using Laravel's FormRequest validation. Here's an example of how you can validate an array of objects:

  1. Create a new FormRequest class by running the following command in your terminal:
1
php artisan make:request YourRequestName


  1. Open the newly created FormRequest class (located in the app/Http/Requests directory) and add the validation rules for your array of objects in the rules() method. For example, if you have an array of products with each product having a name and price attribute, you can set the validation rules like this:
1
2
3
4
5
6
7
8
public function rules()
{
    return [
        'products' => 'required|array',
        'products.*.name' => 'required|string',
        'products.*.price' => 'required|numeric',
    ];
}


  1. Use the FormRequest class in your controller to validate the incoming request. For example, in your controller method:
1
2
3
4
public function store(YourRequestName $request)
{
    // Your logic
}


Now, when you make a request with an array of objects (e.g., using JSON in the request body), Laravel will automatically validate each object in the array according to the rules defined in the FormRequest class. If the validation fails, Laravel will return the validation errors in the response.