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.

Similar Posts