How to validate an array in laravel?

Member

by deron , in category: PHP Frameworks , 14 days ago

How to validate an array in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 13 days ago

@deron 

In Laravel, you can validate an array by using the "array" rule in the validation rules. Here's an example of how to validate an array in Laravel:

1
2
3
$validatedData = $request->validate([
    'array_field' => 'required|array',
]);


In this example, 'array_field' is the name of the field that contains the array data in the request. The 'array' rule will ensure that the value of 'array_field' is an array. If the validation fails, Laravel will automatically redirect back with the validation errors.


You can also add more specific rules to validate the individual elements of the array. For example, if you want to validate that each element in the array is a string, you can do this:

1
2
3
$validatedData = $request->validate([
    'array_field.*' => 'required|string',
]);


In this example, the '*' wildcard character at the end of 'array_field' indicates that each element in the array should be validated individually. The 'required|string' rule ensures that each element is a required string.


You can add more validation rules to suit your specific requirements.