Validation is one of the most important aspect when creating an application. It validates the incoming data from a user. Laravel provides several different ways to validate an application’s incoming data. The most common one is to use the validate
method which can be applied on all incoming HTTP requests. However, we will also discuss other ways for validation in Laravel.
Example of Validation in Laravel
A simple example of validation in Laravel can be the validation of the input fields of data coming from a form. You can apply Validation rules to any function in the controller, which gets in data from the input fields. The validate
method provided by the Illuminate\Http\Request
object is used for this.
Route::post('/user', [PostController::class, 'save']);
Laravel routes shown above return the user data in the return object.
public function save(Request $request)
{
$validated = $request->validate([
'name' => 'required|max:255',
'address' => 'required',
]);
}
You can add the above code in a Laravel controller. It returns user data, for example name and address in the request object and validated before saved. The $request->validate() function takes in the name and address parameters and validates them. This adds validation criteria for each parameter.
For example, the ‘required|max:255’ assures if the name is not empty and has less than 255 characters.
You can do similar validations to check a contact or email address. For example, assure if a contact has numbers, numbers with some code or an email has the required characters (@, .com, etc.).
If a validation passes, the controller will continue code execution normally. A proper response it will automatically generate on validation failure.
In case, if the incoming request is an XHR request, it returns a JSON response. This contains the validation error messages.
You can also pass validation rules as arrays.
$validatedData = $request->validate([
'name' => ['required', 'max:255'],
'contact' => ['required'],
]);
This is an alternate way of passing the validation criteria.
The validateWithBag
method allows you to validate a request and store the error messages in a named error bag.
$validatedData = $request->validateWithBag('user', [
'name' => ['required', 'max:255'],
'contact' => ['required'],
]);
However, if you wish to stop running validation rules after the first failure, the bail
rule can be assigned to that attribute.
$request->validate([
'name' => 'bail|required|max:255',
'contact' => 'required',
]);
In the example above, if the required
on the name
attribute fails, the max
rule to check characters will not be checked. Rules will validate in the order we assign them.
Nested Attributes Validation in Laravel
If an incoming HTTP request has “nested” field data, you may specify these fields with your validation rules using “dot” syntax, as shown below.
$request->validate([
'name' => 'required|max:255',
'user.name' => 'required',
'user.contact' => 'required',
]);
Display of Validation Errors in Blade
An $errors
variable is shared with all blades of the application by the Illuminate\View\Middleware\ShareErrorsFromSession
middleware. This is provided by the web
middleware group. When the middleware is used, the $errors
variable will always be available in view blades, it allows you to conveniently assume that the $errors
variable is always defined and can be safely used. The $errors
variable will be an instance of Illuminate\Support\MessageBag
.
<h1>Create User</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
As shown in the example above, a user will be redirected to the controller’s create
method when validation fails, and displays the error messages in the view.