Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

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

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • 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 46 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Testing Forms and Validation in Laravel: A Practical Guide

Stop manually testing your forms. Learn how to use Laravel's testing suite to automate validation checks, simulate authenticated users, and ensure data integrity.

LaravelTestingPHPValidationAutomationWeb Developmentbackend

Previously in this course, we covered the Introduction to Testing: Build Confident Laravel Apps, where we set up our environment and performed basic status code checks. Now that you have the foundation, we’ll move into the core of any application: testing forms and validation.

Manual testing is a trap. Every time you change a validation rule or update a form field, you risk breaking your application. Automation is your safety net, ensuring that your logic holds up under pressure.

Testing Success Scenarios

When we test a form submission, we are essentially simulating a user filling out an HTML form and hitting "Submit." In Laravel, we use the post() method to simulate this request.

To verify success, we need to check two things: the HTTP response (did we get redirected?) and the database state (did the data actually save?).

Consider a TaskController that handles storing new tasks. Here is how we test that a valid task is created:

PHP
public function test_user_can_create_a_task()
{
    $user = User::factory()->create();

    $this->actingAs($user)
         ->post('/tasks', [
             'title' => 'Learn Laravel Testing',
             'description' => 'Master form validation tests',
         ])
         ->assertRedirect('/tasks');

    $this->assertDatabaseHas('tasks', [
        'title' => 'Learn Laravel Testing',
        'user_id' => $user->id,
    ]);
}

Using actingAs for Authentication

The actingAs() method is a powerful helper that authenticates a specific user for the duration of the test. Since our Task Manager app requires users to be logged in to create tasks, this is mandatory. Without it, the application would redirect the user to the login page, and our assertRedirect('/tasks') would fail.

Testing Validation Error Scenarios

Just as important as testing that things work is testing that they fail correctly. If a user submits a task without a title, we expect the application to stop them and return them to the form with an error.

Laravel makes this easy with assertSessionHasErrors().

PHP
public function test_task_creation_requires_a_title()
{
    $user = User::factory()->create();

    $this->actingAs($user)
         ->post('/tasks', [
             'title' => '', #6A9955">// Empty title
             'description' => 'This should fail',
         ])
         ->assertSessionHasErrors(['title']);

    $this->assertDatabaseCount('tasks', 0);
}

Notice the assertDatabaseCount check. This is a crucial "negative test." It confirms that even though the request was sent, the application correctly prevented the record from entering your database.

Hands-on Exercise: Testing Your Task Manager

Now it's your turn to advance the project. Open your tests/Feature/TaskTest.php file and follow these steps:

  1. Create a test method test_task_description_is_optional.
  2. Use actingAs() to log in as a user.
  3. Submit a POST request to /tasks with only a title (no description).
  4. Assert that the request redirects to the index page.
  5. Assert that the database contains the task with a null description.

This exercise forces you to consider which fields are truly required versus those that are optional in your business logic.

Common Pitfalls

Even experienced engineers hit these snags when starting with automated testing:

  • Forgetting the CSRF Token: Laravel’s web middleware expects a CSRF token. When using post(), Laravel automatically handles this for you. If you ever find yourself getting a 419 Page Expired error in your tests, ensure your route is in routes/web.php and not routes/api.php.
  • Database State Pollution: Your tests should be isolated. Always use the Illuminate\Foundation\Testing\RefreshDatabase trait at the top of your test class. This ensures that every test starts with a fresh, empty database, preventing data from one test from leaking into another.
  • Testing Too Much: Don't test the framework. You don't need to test that Laravel's required validation rule works—the framework developers already did that. Test your business logic, such as your specific validation rules or custom logic in your controller.

Recap

Testing forms and validation is about building confidence. By using actingAs() to handle authentication, post() to simulate submissions, and assertSessionHasErrors() to verify your constraints, you create a suite that protects your app from regressions.

Remember, these tests act as documentation for your code. If a future developer wonders if a task description is required, they can simply look at your test file to find the answer.

Up next: We will explore how to ensure data integrity across multiple operations using Database Transactions.

Previous lessonIntroduction to TestingNext lesson Using Database Transactions
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

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.

Part of the course

Laravel Fundamentals: From Zero to Your First App

beginner · Lesson 46 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, 20263 min read

Handling Global Exceptions in Laravel: A Practical Guide

Learn how to handle global exceptions in Laravel, customize 404/500 error pages, and implement robust logging to keep your Task Manager app stable and professional.

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

    3 min
  • 27

    Understanding CSRF Protection

    3 min
  • 28

    Preventing Mass Assignment

    3 min
  • 29

    Task Manager: Securing the Application

    3 min
  • 30

    Introduction to Route Model Binding

    3 min
  • 31

    Updating Existing Records

    3 min
  • 32

    Deleting Records

    3 min
  • 33

    Using Named Routes

    3 min
  • 34

    Task Manager: Completing CRUD Functionality

    3 min
  • 35

    Introduction to Database Relationships

    3 min
  • 36

    Querying Related Data

    4 min
  • 37

    Handling File Uploads

    3 min
  • 38

    Using Flash Messages for User Feedback

    3 min
  • 39

    Task Manager: Adding Status and Priorities

    3 min
  • 40

    Introduction to Artisan Commands

    3 min
  • 41

    Debugging with Laravel Tinker

    3 min
  • 42

    Understanding Service Providers

    4 min
  • 43

    Using View Composers

    3 min
  • 44

    Task Manager: Refactoring for Clean Code

    3 min
  • 45

    Introduction to Testing

    3 min
  • 46

    Testing Forms and Validation

    3 min
  • 47

    Using Database Transactions

    3 min
  • 48

    Handling Global Exceptions

    3 min
  • 49

    Preparing for Production

    3 min
  • 50

    Environment Security Best Practices

    4 min
  • 51

    Managing Assets in Production

    Coming soon
  • 52

    Task Manager: Deployment Preparation

    Coming soon
  • View full course