Skip to main content
Laravel Basics Tutorial
CHAPTER 12 Beginner

Laravel Validation and Error Handling

Updated: May 14, 2026
20 min read

# CHAPTER 12

Laravel Validation and Error Handling

1. Introduction

The number one rule of backend development is: Never trust user input. If you expect a user to type their age, they might type the word "Banana." If you expect an email, they might leave it blank. If you send this garbage data to your MySQL database, the application will crash. In this chapter, we will learn how to intercept incoming requests, validate the data against strict rules, and gracefully return helpful error messages to the user if the rules are broken.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the $request->validate() method in a Controller.
  • Apply multiple validation rules (required, unique, min/max length).
  • Display validation error messages in Blade views.
  • Understand how Laravel handles automatic redirection upon failure.

3. Beginner-Friendly Explanation

Imagine a bouncer at a nightclub. A teenager tries to walk in. The bouncer checks their ID. The rule is: age must be > 21. The teenager is 18. The bouncer doesn't just punch the teenager and burn the nightclub down (a Fatal PHP Error). The bouncer calmly steps in front of the teenager, turns them around, sends them back to the end of the line, and says, "Sorry, you must be 21 to enter." Laravel's Validation is the bouncer. It intercepts the data, checks the rules, and if the data fails, it automatically redirects the user back to the form with a polite red error message.

4. Basic Validation in the Controller

Validation happens the exact moment the data hits the Controller method.

app/Http/Controllers/PostController.php

php
1234567891011121314151617
public function store(Request $request)
{
    // 1. The Bouncer checks the rules
    $validatedData = $request->validate([
        'title' => 'required|max:255', // Must not be empty, max 255 chars
        'content' => 'required|min:10', // Must be at least 10 chars
        'author_email' => 'required|email|unique:users,email' // Must be a valid email, and unique in the users table
    ]);

    // 2. If the data FAILS, Laravel automatically stops executing here.
    // It instantly redirects the user back to the form with errors attached to the session.

    // 3. If the data PASSES, execution continues and we save to the database!
    Post::create($validatedData);

    return redirect('/posts')->with('success', 'Post created safely!');
}

5. Displaying Errors in Blade

When Laravel redirects a user back due to a validation failure, it flashes an $errors variable to the Blade View. We can use the @error directive to display specific error messages next to the input fields.

resources/views/posts/create.blade.php

html
123456789101112131415161718192021
<form method="POST" action="/posts">
    @csrf

    <label>Title</label>
    <!-- We use the old() helper so the user doesn&#039;t lose what they typed! -->
    <input type="text" name="title" value="{{ old(&#039;title') }}">
    
    <!-- Display the specific error for &#039;title' -->
    @error(&#039;title')
        <div style="color: red;">{{ $message }}</div>
    @enderror

    <label>Content</label>
    <textarea name="content">{{ old(&#039;content') }}</textarea>
    
    @error(&#039;content')
        <div style="color: red;">{{ $message }}</div>
    @enderror

    <button type="submit">Save</button>
</form>

6. Displaying a Summary of All Errors

Sometimes it's easier to just show a big red box at the top of the form containing a bulleted list of all errors.
html
123456789
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

7. Customizing Error Messages

By default, Laravel generates messages like "The title field is required." If you want to customize this, you can pass a second array to the validate method.
php
1234
$request->validate(
    [&#039;title' => 'required'],
    [&#039;title.required' => 'Hey! You forgot to type a headline!']
);

8. Exception Handling

What if a database server goes offline? This isn't a validation error; it's a critical Exception. Laravel handles all exceptions in app/Exceptions/Handler.php. By default, if the app is in "Local" mode (in your .env), it shows a detailed stack trace (Ignition error page). If the app is in "Production" mode (APPENV=production, APPDEBUG=false), Laravel hides the stack trace and automatically shows a friendly 500 Server Error page to the user.

9. Best Practices

  • Never Trust Frontend Validation: Adding required to your HTML <input> tags is great for user experience, but it is not security. Hackers bypass HTML and send POST requests directly via Postman. You MUST validate on the backend in Laravel.

10. Common Mistakes

  • Losing User Data on Redirect: If a user types a 500-word blog post, but forgets to enter the Title, Laravel redirects them back. If you do not use the old('content') helper in your <textarea>, the 500 words will be erased, and the user will be furious. Always use old('field_name') to repopulate forms.

11. Exercises

  1. 1. Trace the execution flow: A user submits a form without an email address. The Controller dictates that the email is required. What exactly does Laravel do next?

12. Coding Challenges

  • Challenge: Write the validation rules for a Registration form. The username must be required, alphanumeric, and unique in the users table. The password must be required and at least 8 characters long.

13. MCQs with Answers

Question 1

What happens when data fails the $request->validate() method in a Laravel Controller?

Question 2

Which Blade helper function is used to repopulate an HTML input field with the user's previously typed data after a validation failure?

14. Interview Questions

  • Q: Explain how Laravel's $request->validate() method protects a database from bad data.
  • Q: If an attacker bypasses client-side HTML validation, how does Laravel's backend validation ensure the application remains secure, and how is the unique:table,column rule critical for user registration?

15. FAQs

Q: My controller is getting too fat with 30 validation rules. Can I move them? A: Yes! Advanced developers use "Form Request Classes." You run php artisan make:request StorePostRequest. This creates a dedicated file just for your validation rules, keeping your Controller perfectly clean.

16. Summary

In Chapter 12, we enforced the golden rule of the backend: never trust user input. By utilizing Laravel's elegant validation syntax, we erected a secure checkpoint before our database. We learned how to enforce complex constraints like uniqueness and length, how to leverage Blade's @error and old() directives to provide a seamless user experience, and how Laravel handles automatic redirection upon failure.

17. Next Chapter Recommendation

Validation intercepts the request inside the Controller. But what if we want to intercept the request *before* it even reaches the Controller? Proceed to Chapter 13: Middleware and Request Lifecycle.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·