Mahamudul Hasan Rubel
HomeAboutProjectsSkillsExperienceBlogCoursesPhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • About
  • Projects
  • Skills
  • Experience
  • Blog
  • Courses
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 22 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Introduction to Laravel Validation: A Beginner's Guide

Learn how to use Laravel validation to ensure data integrity. Discover how to apply rules, handle failures, and display error messages in your Blade views.

LaravelPHPValidationWeb DevelopmentBeginnersbackend

Previously in this course, we learned how to capture user input from forms. While retrieving data is the first step, trusting that data is a recipe for disaster. In this lesson, we’ll move from simply accepting input to verifying it using Laravel’s built-in validation system.

Why Validation Matters

In a production application, you never trust user input. If your Task Manager app expects a task title, what happens if a user submits an empty string or a script tag? Without validation, you’d save garbage data to your database, potentially breaking your UI or exposing your application to security risks.

Laravel makes validation incredibly simple by providing a fluent, expressive interface. Instead of writing complex if/else statements, you define a set of rules, and Laravel handles the rest.

Applying Basic Validation Rules

To validate a request, you use the $request->validate() method within your controller. This method accepts an array of rules where the key corresponds to the input field name.

Let's update our TasksController to ensure the title field is present and has a minimum length. Open app/Http/Controllers/TasksController.php and update your store method:

PHP
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|max:255',
        'description' => 'nullable|string',
    ]);

    #6A9955">// If validation passes, execution continues here
    Task::create($validatedData);

    return redirect('/tasks');
}

In this example:

  • required: The field must be present and not empty.
  • max:255: The field cannot exceed 255 characters.
  • nullable: The field is optional, but if provided, it must be a string.

Handling Validation Failures

What happens if the user submits an empty form? Laravel automatically detects that the validation failed. It stops the execution of your controller method and redirects the user back to their previous location.

Crucially, it also flashes the validation errors and the old input data into the session. This means you don't have to manually redirect or carry over the user's input—Laravel handles this infrastructure for you.

Displaying Error Messages in Blade

Now that the errors are in the session, we need to show them to the user. Laravel makes this easy with the $errors variable, which is automatically available in all your Blade views.

Open the view file where your form lives (e.g., resources/views/tasks/create.blade.php) and add the following code above your form:

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

<form action="/tasks" method="POST">
    @csrf
    <input type="text" name="title" value="{{ old('title') }}">
    
    @error('title')
        <div class="text-red-500">{{ $message }}</div>
    @enderror

    <button type="submit">Create Task</button>
</form>

Key concepts used here:

  1. $errors->any(): Checks if there are any validation errors.
  2. @foreach ($errors->all()): Iterates through all errors to display them in a list.
  3. old('title'): Repopulates the input field with the user's previous input so they don't have to re-type it.
  4. @error('title'): A convenient directive to display an error message for a specific field.

Hands-on Exercise

  1. Add a priority field to your task creation form.
  2. In your TasksController, add a validation rule to ensure the priority field is required and must be an integer.
  3. Update your Blade template to display a specific error message if the user enters a non-numeric value for the priority.

Common Pitfalls

  • Forgetting @csrf: If you forget the @csrf directive in your form, your request will fail with a 419 Page Expired error before validation even runs.
  • Over-validating: Avoid complex logic in the controller. If your validation logic grows, consider using Laravel FormRequest Custom Error Messages: A Beginner’s Guide to keep your controllers clean.
  • Ignoring old(): Users get frustrated when they submit a form, see an error, and find their entire form cleared. Always use the old() helper to maintain a good user experience.

Recap

Validation is your first line of defense against bad data. By using $request->validate(), you ensure your application only processes clean, expected input. When validation fails, Laravel’s automatic redirect and the global $errors variable allow you to provide instant, helpful feedback to your users, making your application significantly more robust.

Up next: We'll dive into Customizing Validation Error Messages to provide a more polished experience for our users.

Previous lessonCapturing User Input from FormsNext lesson Customizing Validation Error Messages
Back to Blog

Similar Posts

LaravelJune 25, 20263 min read

Customizing Validation Error Messages for Better Laravel UX

Learn to customize Laravel validation error messages to provide clear, helpful feedback to your users. Master field-specific errors and language files.

Read more
LaravelJune 25, 20263 min read

Using Form Requests for Validation: A Laravel Beginner Guide

Learn how to use Form Requests in Laravel to move validation logic out of your controllers. Keep your code clean, DRY, and professional with this guide.

Part of the course

Laravel Fundamentals: From Zero to Your First App

beginner · Lesson 22 of 52

  1. 1

    Setting Up the Local Development Environment

    4 min
  2. 2

    Installing Laravel and Exploring Directory Structure

    3 min
  3. 3

    Understanding the .env File and Configuration

    3 min
Read more
LaravelJune 25, 20264 min read

Capturing User Input from Forms: A Laravel Beginner's Guide

Learn how to build HTML forms and use the Request object to handle user input in your Laravel application. Master input handling for your project.

Read more
  • 4

    The Laravel Application Lifecycle

    4 min
  • 5

    Initializing the Task Manager Project

    3 min
  • 6

    Defining Basic Web Routes

    4 min
  • 7

    Using Route Parameters

    3 min
  • 8

    Creating Your First Controller

    3 min
  • 9

    Returning Responses and Redirects

    3 min
  • 10

    Task Manager: Implementing the Task List Route

    3 min
  • 11

    Introduction to Blade Templating

    3 min
  • 12

    Using Blade Layouts and Sections

    3 min
  • 13

    Implementing Blade Partials

    4 min
  • 14

    Mastering Blade Directives for Loops and Conditionals

    3 min
  • 15

    Task Manager: Building the User Interface

    3 min
  • 16

    Understanding Database Migrations

    3 min
  • 17

    Working with Eloquent Models

    3 min
  • 18

    Performing Basic CRUD Operations

    3 min
  • 19

    Seeding the Database

    3 min
  • 20

    Task Manager: Displaying Real Database Records

    3 min
  • 21

    Capturing User Input from Forms

    4 min
  • 22

    Introduction to Laravel Validation

    3 min
  • 23

    Customizing Validation Error Messages

    3 min
  • 24

    Using Form Requests for Validation

    3 min
  • 25

    Introduction to Authentication

    4 min
  • 26

    Protecting Routes with Middleware

    Coming soon
  • 27

    Understanding CSRF Protection

    Coming soon
  • 28

    Preventing Mass Assignment

    Coming soon
  • 29

    Task Manager: Securing the Application

    Coming soon
  • 30

    Introduction to Route Model Binding

    Coming soon
  • 31

    Updating Existing Records

    Coming soon
  • 32

    Deleting Records

    Coming soon
  • 33

    Using Named Routes

    Coming soon
  • 34

    Task Manager: Completing CRUD Functionality

    Coming soon
  • 35

    Introduction to Database Relationships

    Coming soon
  • 36

    Querying Related Data

    Coming soon
  • 37

    Handling File Uploads

    Coming soon
  • 38

    Using Flash Messages for User Feedback

    Coming soon
  • 39

    Task Manager: Adding Status and Priorities

    Coming soon
  • 40

    Introduction to Artisan Commands

    Coming soon
  • 41

    Debugging with Laravel Tinker

    Coming soon
  • 42

    Understanding Service Providers

    Coming soon
  • 43

    Using View Composers

    Coming soon
  • 44

    Task Manager: Refactoring for Clean Code

    Coming soon
  • 45

    Introduction to Testing

    Coming soon
  • 46

    Testing Forms and Validation

    Coming soon
  • 47

    Using Database Transactions

    Coming soon
  • 48

    Handling Global Exceptions

    Coming soon
  • 49

    Preparing for Production

    Coming soon
  • 50

    Environment Security Best Practices

    Coming soon
  • 51

    Managing Assets in Production

    Coming soon
  • 52

    Task Manager: Deployment Preparation

    Coming soon
  • View full course