How to validate array in Laravel?
In Laravel, you can use the validate
method on the Validator
facade to validate an array of form data. The validate
method accepts the following arguments:
- The request data to be validated (e.g.
$request->all()
) - An array of validation rules
Here's an example of how you can use the validate
method to validate an array of form data:
<?php
use Validator;
...
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return redirect('form')
->withErrors($validator)
->withInput();
}
// The form data is valid, you can continue processing it...
The make
method on the Validator
facade creates a new validator instance with the given data and validation rules. The fails
method checks if the validation failed, and if it did, you can redirect the user back to the form with the validation errors and their input using the withErrors
and withInput
methods.
You can also use the validate
method as a route middleware to validate form data before a request is handled by the route closure or controller action.
<?php
Route::post('form', function (Request $request) {
// The form data is already validated...
})->middleware('validate:name,email,password');
In this example, the validate
middleware will validate the name
, email
, and password
fields of the request data. If the validation fails, a HTTP response with the validation errors will be automatically generated.