Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user.
Defining The Routes
1.First, let's assume we have the following routes defined in our routes/web.php
file:
Route::get('post/create', 'PostController@create');
Route::post('post', 'PostController@store');
The GET
route will display a form for the user to create a new blog post, while the POST
route will store the new blog post in the database.
php artisan make:controller PostController
Creating The Controller
3.Open app\Http\PostController.php and Implement code as below
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function Create(){
return view('form');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Validation In Laravel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="text-center">
<h1>Validation In Laravel</h1>
</div>
<h2></h2>
<div class="form-group col-sm-2"></div>
<div class="form-group col-sm-8">
<div class="well">
<form method="post" action="{{url('formstore')}}">
@csrf
<div class="form-group col-sm-12">
<label>Title</label>
<input class="form-control" type="text" name="title" value="">
</div>
<div class="form-group col-sm-12">
<label>Body</label>
<textarea class="form-control" type="textarea" name="body" ></textarea>
</div>
<div class="form-group text-center">
<input class="btn btn-primary" type="submit" >
</div>
</form>
<div class="form-group col-sm-2"></div>
</div>
</div>
<br>
</div>
</body>
</html>
Writing The Validation Logic
Now we are ready to fill in our store
method with the logic to validate the new blog post. To do this, we will use the validate
method provided by the Illuminate\Http\Request
object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.
To get a better understanding of the validate
method, let's jump back into the store
method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function Create(){
return view('form');
}
public function store(Request $request){
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
}
}
As you can see, we pass the desired validation rules into the validate
method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.
Alternatively, validation rules may be specified as arrays of rules instead of a single |
delimited string:
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
You may use the validateWithBag
method to validate a request and store any error messages within a named error bag:
$validatedData = $request->validateWithBag('post', [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
Stopping On First Validation Failure
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail
rule to the attribute:
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required',
]);
In this example, if the unique
rule on the title
attribute fails, the max
rule will not be checked. Rules will be validated in the order they are assigned.
A Note On Nested Attributes
If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
Displaying The Validation Errors
So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error messages to the view in our GET
route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors
variable will be an instance of Illuminate\Support\MessageBag
. For more information on working with this object, check out its documentation.
So, in our example, the user will be redirected to our controller's create
method when validation fails, allowing us to display the error messages in the view:
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- Create Post Form -->
The @error
Directive
You may also use the @error
Blade directive to quickly check if validation error messages exist for a given attribute. Within an @error
directive, you may echo the $message
variable to display the error message:
<!-- /resources/views/post/create.blade.php -->
<label for="title">Post Title</label>
<input id="title" type="text" class="@error('title') is-invalid @enderror">
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
A Note On Optional Fields
TrimStrings
and ConvertEmptyStringsToNull
middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel
class. Because of this, you will often need to mark your "optional" request fields as nullable
if you do not want the validator to consider null
values as invalid. For example:
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]);
publish_at
field may be either null
or a valid date representation. If the nullable
modifier is not added to the rule definition, the validator would consider null
an invalid date.AJAX Requests & Validation
In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using thevalidate
method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
Route::get('post/create', 'PostController@create');
Route::post('post', 'PostController@store');
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function Create(){
return view('create');
}
public function store(Request $request){
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Validation In Laravel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="text-center">
<h1>Validation In Laravel</h1>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="form-group col-sm-2">
</div>
<div class="form-group col-sm-8">
<div class="well">
<form method="post" action="{{url('post')}}">
@csrf
<div class="form-group col-sm-12">
<label for="title">Post Title</label>
<input id="title" type="text" class="form-control @error('title') is-invalid @enderror">
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group col-sm-12">
<label>Body</label>
<textarea class="form-control @error('body') is-invalid @enderror" type="textarea" name="body" ></textarea>
@error('body')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group text-center">
<input class="btn btn-primary" type="submit" >
</div>
</form>
<div class="form-group col-sm-2"></div>
</div>
</div>
<br>
</div>
</body>
</html>