Displaying Error Messages in Blade

Tutorial 3 of 5

Introduction

In this tutorial, we will be discussing how to display validation error messages within Laravel's Blade templating engine. This is a necessary skill for any web developer, as it helps users understand what went wrong when filling out forms on your web application.

By the end of this tutorial, you will learn how to:

  • Validate user inputs in Laravel
  • Display validation error messages in Blade templates
  • Customize error messages

Prerequisites:

  • Basic knowledge of PHP
  • Familiarity with Laravel and Blade templating engine

Step-by-Step Guide

Validation in Laravel

Before we delve into displaying error messages, it's important to understand validation in Laravel. Laravel's validation features provide various ways to validate incoming data. You can easily perform validation using Laravel's Validator class.

Displaying Error Messages

After validating data, Laravel will automatically redirect the user back to their previous location with all of the validation error messages stored in the session. Therefore, you can display these errors in your Blade templates.

Code Examples

Basic Display of Errors

First, let's look at a simple way to display all error messages:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

In the above code:

  • We're checking if there are any errors present with $errors->any()
  • If there are errors, we're creating a div to hold them
  • We're then looping through each error and displaying it in a list item

Displaying Individual Field Errors

You can also display errors for individual fields:

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Here:

  • We use the @error directive to check if there are any errors for the 'title' field
  • If there are, we display them in a div

Summary

In this tutorial, we learned how to validate user input in Laravel and display validation error messages in Blade templates. We also learned how to customize these messages.

For further learning, you can explore more about Laravel's validation rules and how to create custom validation rules.

Practice Exercises

  1. Create a form with fields for 'name', 'email', and 'password', and display validation errors for each field.
  2. Modify the validation rules for the form you created in exercise 1. The 'name' field should be required and at least 5 characters long. The 'email' field should be a valid email address. The 'password' field should be required and at least 8 characters long.
  3. Display a success message if form validation passes successfully.

Additional Resources