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.

Similar Posts