Laravel form validation is a process where Laravel validates the data sent by the end-user to the application to ensure that the user sends the right data with the format needed for the application. It also ensures that the application is protected from malicious input.
Let’s look at a simple example of how to validate form data and display errors. This example is based on a form where users send suggestions for improvements in a company.
Route::get('suggestion/create', 'SuggestionController@create');
Route::post('suggestion', 'SuggestionController@store');
The GET route
will display a form for the user to send their suggestion, while the POST route
will store the suggestion in the database.
The validation comes when we want to store the suggestion in the database to restrict and ensure certain values.
Controller
classLet’s dive into the controller
:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class SuggestionController extends Controller {
public function create() {
return view('suggestion.create');
}
public function store(Request $request) {
$validatedData = $request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
}
}
In the store()
method, we define rules to validate the input data.
From the code above, we see that the title
has been set to required
because a user can disable it from the browser, which will be enforced before it is sent to the database.
We can also see that max:255
limits the data size.
Validation is done by passing rules into the validate()
method. The rules above can be passed into an array method.
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
If the parameters do not pass the given validation rules, Laravel will automatically redirect the user to their previous location with all the errors flashed to the session
.
The errors flashed to the
session
is an instance of theIlluminate\Support\MessageBag
class.
The $error
is bound to the view by the web
middleware group, so as long as you use the web middleware $error
variable, it will always be available in your view.
Let’s see how we can display the error(s) on validation failure.
Use the @error
Blade directive to quickly check if validation error messages exist for a given input field.
Within an @error
directive, we echo the $message
to display errors for a different input field.
<!-- /resources/views/suggestion/create.blade.php -->
<label for="title">Post Title</label>
<input id="title" type="text"title') is-invalid @enderror">
@error('title')
<div>{{ $message }}</div>
@enderror
Laravel form validation is the process where Laravel restricts certain data and ensures that the right data, in its right format, is stored in the database while displaying the errors of wrong data input.
The validation is done by calling the validate()
method in the controller
.