Mastering Laravel Form Requests: Several Techniques for Cleaner Validation

laravel form request
Home » Blog » Mastering Laravel Form Requests: Several Techniques for Cleaner Validation

Mastering Laravel Form Requests: Several Techniques for Cleaner Validation

laravel form request

Laravel Form Requests are custom request classes that move validation logic from web controllers into a class that pre-validates data for you. They also make handling validation easier by moving the validation logic out of the controller and into a separate file. This helps you keep your code clean and organized. A form request

  • centralizes validation rules to keep controller methods focused and clean,
  • determines whether users are authorized to make a request,
  • encapsulates validation rules and error messages, and
  • handles more complex validation scenarios.

What is a Laravel Form Request?

In simple terms, a Form Request is like a special “helper” class that Laravel creates for you. It handles validation for specific forms or requests. Instead of writing validation directly in your controller, you define the validation rules in this “helper” class. It makes your controller more readable and easier to maintain.

Benefits of using Form Requests

A Laravel request comes with multiple benefits. It offers a simplified workflow, organized information at scale, time savings, proper task scheduling, pre-validation, and clean controllers.

When we talk about keeping controllers clean, the Laravel request validation process is handled outside the controller. That is why it makes the controller easier to understand and maintain. Moreover, it offers the added advantage of reusability. You can reuse the same Form Request in different methods if needed (e.g., for updating user info). A form request also plays a vital role in managing things better. When we look at the factor of better organization, it means your validation logic is neatly stored in a separate file.

How Does Laravel Form Request Work?

Laravel Form Request implements the validation step on incoming data. It also enables the authorization logic for the request.

Create a Form Request:

Laravel creates a separate file (Form Request) to handle validation for specific forms. This file will contain the rules for what data is valid and what is not.

Apply Validation:

You define the rules for the form’s fields (e.g., name, email, password) inside the Form Request file. If the user submits invalid data, Laravel will automatically send error messages to the user, just like before.

Use the Form Request in Your Controller:

Instead of manually writing validation rules inside the controller, you use the Form Request.

Why Use Form Requests?

Form requests should be used for cleaner codes, reusability, and easy maintenance. Cleaner code moves the validation logic out of the controller. Reusability allows you to use the same Form Request class in multiple places if needed. It is easier to maintain when your app grows, your validation logic stays organized.

How to Use Laravel Form Requests (Step-by-Step)?

Step 1: Create a Form Request

Laravel provides an artisan command to create a new Form Request file. Run this in your terminal:

php artisan make:request StoreUserRequest

This creates a new file called StoreUserRequest.php in the app/Http/Requests/ directory. This file will handle validation for storing a user.

Step 2: Define Validation Rules in the Form Request

Open the newly created file (StoreUserRequest.php) and define your validation rules inside the rules() method. It might look something like this:

<?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',
        ];
    }
}

authorize(): It confirms if users are legal to make this request. In most cases, you return true to allow the request. You can add conditions here for authorization later if needed.

rules(): This method contains the actual validation rules. Here we are validating that the email is valid with uniqueness in the user’s table, the name field is a string with 255 characters max, and the password field is a string with at least 8 characters.

Step 3: Use the Form Request in the Controller

In your controller, instead of writing validation logic directly, you simply “inject” the Form Request you just created. Here’s how:

<?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,
        // you can focus on your logic to store the data.

        // Create the new user
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

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

Explanation:

StoreUserRequest $request: Instead of using the usual Request $request, we use the StoreUserRequest. This means that Laravel automatically checks the rules in StoreUserRequest and validates the input data before proceeding with the rest of the code.

Laravel validation is automatic: If Laravel form validation fails, Laravel will send back an error response without you having to manually check for errors.

Example Use Case:

Suppose, you create a form for new user registration. With the Form Request, this process becomes much cleaner and easier to manage.

You run the command to create a StoreUserRequest. You define validation rules for the form fields (like email, password) inside StoreUserRequest. In the controller, you just inject the StoreUserRequest, and Laravel automatically handles validation. If validation passes, your controller focuses on storing the user.

Example Error Response:

If the user submits invalid data (for example, an empty email or a password with less than 8 characters), Laravel will automatically return a JSON 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."]
    }
}

The user will see these messages and can correct their input.

Summing up

Laravel Form Requests handle form validation in a clean and organized way. You create a separate file (Form Request) to define your validation rules. In the controller, you use the Form Request instead of manually writing validation logic. Laravel automatically handles errors and sends back error messages to the user.

By using Form Requests, your code stays clean and easy to manage, especially as your application grows. It also helps you focus on handling the business logic (like saving data) rather than worrying about validation inside your controller.

Let’s create something beautiful and
innovative together! call us now!

Chat with our seniors to see if we have a good match

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Request Free Consultation

"*" indicates required fields

BLOG

Our recent post