Validation
Introduction
Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests
trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.
Validation Quickstart
To learn about 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
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.
Creating The Controller
Next, let's take a look at a simple controller that handles these routes. We'll leave the store
method empty for now:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* @return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
}
}
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:
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
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.
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.
The $errors
variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by the web
middleware group. When this middleware is applied an $errors
variable will always be available in your views, allowing you to conveniently assume the $errors
variable is always defined and can be safely used.
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 -->