How to validate array in laravel with request?

Member

by addison , in category: PHP Frameworks , 24 days ago

How to validate array in laravel with request?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 23 days ago

@addison 

To validate an array in Laravel with a request, you can use the validate method provided by the base controller class. Here's an example of how you can validate an array of input data in a controller method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public function store(Request $request)
{
    $validatedData = $request->validate([
        'items.*.name' => 'required|string',
        'items.*.quantity' => 'required|integer|min:1'
    ]);

    // If the input data passes validation, it will be available in the $validatedData array

    // Further processing logic...

}


In this example, we are validating an array of items, where each item should have a name and quantity field. The items.*.name syntax is used to indicate that each item in the array should have a name field, and the required|string validation rule ensures that the name field is a string and is not empty. Similarly, the items.*.quantity field is validated with the rules required|integer|min:1.


If the input data does not pass the validation, Laravel will automatically redirect the user back with validation error messages.