Simplifying Form Validation with Laravel Form Requests

Chandan Kumar
4 min readOct 21, 2024

--

When building web applications, clean and organized code is essential, especially as your project grows. Laravel, a powerful PHP framework, provides an elegant solution for handling form validation with Form Requests. By moving validation logic out of controllers and into their own classes, Laravel Form Requests make your code more maintainable, reusable, and cleaner.

Let’s dive into how Laravel Form Requests can simplify your validation workflow and help you maintain cleaner, more efficient code.

What is a Laravel Form Request?

At its core, a Form Request is a special “helper” class that Laravel generates to handle validation for forms and API requests. Instead of placing validation rules directly in the controller, you define them in this class, keeping your controller focused on the business logic. This improves the readability and maintainability of your application.

Benefits of Using Form Requests:

  • Cleaner code: Moves validation logic out of the controller, improving readability.
  • Reusability: Form Requests can be reused across multiple methods or controllers.
  • Organization: Keeps validation rules neatly separated from business logic.

For a deeper dive into how Laravel Form Requests work and how they benefit developers, check out our detailed blog post.

How Laravel Form Requests Work

Laravel Form Requests implement validation by intercepting incoming data before it reaches the controller. It also handles the authorization logic, allowing you to define whether the request is permitted.

Steps to Use Laravel Form Requests:

Step 1: Create a Form Request

Use Laravel’s artisan command to create a new Form Request file:

artisan make:request StoreUserRequest
This command creates a file called StoreUserRequest.php in the app/Http/Requests/ directory. This file will handle validation for the form or request.

Step 2: Define Validation Rules

Inside the StoreUserRequest.php file, you can define the validation rules using the rules() method. Here’s an example:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
public function authorize()
{
// Set to true to allow all users to make this request
return true;
}

public function rules()
{
// Validation rules
return [
‘name’ => ‘required|string|max:255’,
‘email’ => ‘required|email|unique:users,email’,
‘password’ => ‘required|string|min:8’,
];
}
}

In this example:

  • The authorize() method is used to check if the user is authorized to make the request (returning true for now).
  • The rules() method defines the validation rules. In this case, the name is required, the email must be unique, and the password must have at least 8 characters.

Step 3: Use Form Request in the Controller

In your controller, instead of manually writing validation logic, you inject the Form Request:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;

class UserController extends Controller
{
public function store(StoreUserRequest $request)
{
// Since validation is handled by the Form Request,
// focus on your logic to store the data.

$user = User::create([
‘name’ => $request->name,
‘email’ => $request->email,
‘password’ => bcrypt($request->password),
]);

return response()->json([‘message’ => ‘User created successfully’], 201);
}
}

In this example, StoreUserRequest $request is injected into the controller method. Laravel automatically validates the input data against the rules defined in StoreUserRequest.php before proceeding with the logic to store the user.

Automatic Validation and Error Handling

If the data provided by the user doesn’t meet the validation rules, Laravel automatically halts the request and returns an error response, like this:

{
“message”: “The given data was invalid.”,
“errors”: {
“email”: [“The email field is required.”],
“password”: [“The password must be at least 8 characters.”]
}
}

This allows the user to receive clear feedback on what went wrong and fix the input data.

Why Use Laravel Form Requests?

Using Form Requests offers several benefits, particularly as your application grows:

  • Cleaner Code: By moving validation logic out of the controller, the code becomes easier to understand and maintain.
  • Reusability: You can reuse the same Form Request across multiple methods and controllers if needed.
  • Easier Maintenance: Validation rules are centralized in one place, making it easier to manage and update the logic as needed.

Example Use Case: User Registration Form

Imagine you have a registration form where users submit their name, email, and password. With Laravel Form Requests, this process becomes much more manageable.

  1. Create a StoreUserRequest to handle the validation.
  2. Define validation rules for the form fields (e.g., email, password) inside the StoreUserRequest class.
  3. Inject the Form Request into the controller to handle the validation.

Laravel takes care of the rest by automatically handling validation errors and sending clear error messages back to the user.

Summing Up

Using Laravel Form Requests allows you to handle form validation in a clean, organized way. By separating validation logic into its own class, you can focus on writing business logic in your controller. Form Requests also make your code more maintainable, reusable, and easier to scale as your application grows.

--

--