Elementary Laravel:

Validation consists of two parts, validating the data from the user and displaying the errors messages back to the user.


Out of the box, Laravel comes loaded with validation options and it is also very easy and quick to implement it however you want. In the previous lesson, we have left things off at a contact form. We have created a contact form which submits its data to the URL we specified POST /contact and it is being handled by our route.


This is what we want to happen when the user submits the contact form:

If the data entered passes validation, our application should:

  • send us an email
  • redirect the user to /contact page
  • display success message to the user

If the data entered does not pass validation, our application should:

  • redirect the user to the contact form with old input
  • display errors messages telling the user what he did wrong

Validating data

Back to our routes/web.php file. Locate the route:

Route::post('contact', function() {

First we have to tell our route to use dependency injection to inject the Request like so:

use Illuminate\Http\Request;
Route::post('contact', function(Request $request) {
    // place code here

Now we can access the request, meaning that we can validate the data inside it. We will manually build our Validator but we will also use the Automatic Redirection feature to automatically handle the redirection and error processing if the validation fails.

Place this code inside our POST route:

\Validator::make($request->all(), [
    'name' => 'required|string',
    'email' => 'required|email',
    'comment' => 'required|string'

// normal code execution with successful validation.
// send email or do whatever you want here,
// redirect user back and notify him of our success

Now let me explain. From the Validation documentation:

"If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the ValidatesRequest trait, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned."

As you can see, we are specifying parameter names and validation rules for each.

Improve your skills! To understand and know which other validation rules exist, read the documentation on Available Validation Rules.

This is the current state of the repository at this moment dbc88e6ccae9f8c8b0c92e9b19edb7e3cefd8949.

Displaying errors

If you try to submit the form now with no data, you will be redirected back to out /contact page and it will seem like nothing happened, but in fact, the validation was triggered and it failed because it did not pass our validation rules. required validation rule means that the field under inspection must have some data in it. If you populate all fields in our contact form correctly and submit the form you should get a blank page again.

The smart thing to do here is to provide the user some information on why the validation has failed. In the Validation documentation under Displaying The Validation Errors is this snippet:

@if (count($errors) > 0)
    <div class="alert alert-danger">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>

This snippet loops through all the errors (if any) in the session and displays them in an unordered list (Twitter Bootstrap styling, but you can modify it however you want). Place this snippet just above the form tag in resources/views/contact.blade.php.

Now if you try to submit the form with no data, you should get a page which looks like this:

Failed Validation

Try messing around with different values to see how it works.

This is the current state of the repository at this moment 62b5b9d7defe9366a97e69c1772371ddfa786350.

The validation is now working. We are successfully validating the data and displaying errors to the user. We still have to process what happens if the validation is successful.

Follow the happy path

We want to redirect the user to the contact form (empty) and display a success message signaling that everything went ok.

In resources/views/contact.blade.php, just bellow our validation code place the following:

return redirect('/contact')->with([
    'success_message' => 'Your message has been sent!'

This code redirects the user to the /contact page. It also flashes session data with a variable called success_message. That variable will be available on our page.

Now to catch that variable on our contact page, we have to add this block of code to the place where we want it to be displayed:

@if (session('success_message'))
    <div class="alert alert-success">
        {{ session('success_message') }}

Add this code just above the form tag in contact.blade.php. If you populate the form now with data and submit it, you will be presented with this nice little green alert box:

Success Message

This is the current state of the repository at this moment 8c4b2c8d534a7d101951fae2f04e6b2cce129fae.

This completes this lesson. Our contact form is now working, the only thing left is actually sending the email :) This will be done in the following lesson. Until next time... happy learning!