Learn Laravel · 10/17

Advanced Validation & Form Requests: Keeping Data Clean

8 min read

Advanced Validation & Form Requests: Keeping Data Clean 🧼

Welcome back to our journey with Laravel! Today, we're diving into a crucial aspect of any web application: ensuring the data we receive is clean, valid, and secure. Think of your application as a high-end restaurant. You wouldn't let just any ingredients into your kitchen, would you? Of course not! You'd have a strict process to check the quality of everything that comes through the door. In the world of web development, that's what validation is all about.

The Problem: Without proper validation, your application's database can quickly become a messy place filled with incorrect, incomplete, or even malicious data. This can lead to bugs, security vulnerabilities, and a very unhappy user experience. Imagine a user signing up with an invalid email address and then wondering why they never receive any notifications. Not a good look!

The Solution: Laravel provides a powerful and elegant way to handle data validation, ensuring that only pristine data makes it into your application. We're going to explore how to level up our validation game using Form Requests and some advanced validation rules.


1. Extracting Logic: Creating Custom Form Request Classes 📦

As your application grows, you might find your controller methods getting cluttered with validation logic. This can make them hard to read and maintain. It's like trying to cook a gourmet meal in a tiny, disorganized kitchen.

The Problem: Look at this controller method. The validation logic is right in the middle of everything, making the controller do more than it should (handling the request and validating it).

php
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // ... create the post
}

This isn't terrible for a small application, but imagine having ten or fifteen validation rules. It would become a nightmare to manage.

The Solution: Laravel's Form Request classes allow us to extract this validation logic into its own dedicated class. This cleans up our controllers and makes our validation logic reusable. It's like having a dedicated quality control station in our restaurant's kitchen.

Let's create a Form Request class. Open your terminal and run the following Artisan command:

bash
php artisan make:request StoreBlogPostRequest

This command will generate a new file at app/Http/Requests/StoreBlogPostRequest.php. Let's take a look inside.

php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreBlogPostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return false; // We'll talk about this soon!
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            // Our validation rules will go here
        ];
    }
}

Now, we can move our validation rules from the controller to the rules method of our new StoreBlogPostRequest class.

php
// app/Http/Requests/StoreBlogPostRequest.php

public function rules(): array
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

And our controller method becomes beautifully clean and simple. All we need to do is type-hint our StoreBlogPostRequest class in the controller method. Laravel's service container will automatically resolve it and perform the validation before our controller code is even executed! ✨

php
// app/Http/Controllers/PostController.php

use App\Http\Requests\StoreBlogPostRequest;

public function store(StoreBlogPostRequest $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();

    // ... create the post using $validated data
}

If the validation fails, Laravel automatically redirects the user back to the previous page with all the validation error messages. It's like magic, but better, because it's code!


2. Writing Complex Validation Rules (Unique, Exists, Regex) 🧐

Basic validation rules like required and max are great, but sometimes we need more powerful tools to ensure our data is just right. Let's look at a few advanced rules that are commonly used in the industry.

The unique Rule

This rule ensures that a given field's value doesn't already exist in a specific database table. It's perfect for things like user emails or blog post slugs.

Scenario: We're building a blog, and we want to make sure every post has a unique title.

php
'title' => 'required|unique:posts|max:255',

Here, unique:posts tells Laravel to check the posts table and ensure the title is unique.

But what about updating a post? If we use the same rule when updating, it will fail because the title already exists for the post we are trying to update! 🤯 To solve this, we can tell the unique rule to ignore a specific ID.

php
use Illuminate\Validation\Rule;

public function rules(): array
{
    return [
        'title' => [
            'required',
            Rule::unique('posts')->ignore($this->post->id),
            'max:255',
        ],
        'body' => 'required',
    ];
}

In this example, $this->post->id refers to the ID of the post being updated. Now, the validation will pass if the title belongs to the current post.

The exists Rule

The exists rule is the opposite of unique. It checks if a value does exist in another database table. This is incredibly useful for validating foreign keys.

Scenario: When creating a blog post, we want to assign it to a category. We need to make sure that the category_id provided in the request actually corresponds to a real category in our categories table.

php
'category_id' => 'required|exists:categories,id',

This rule ensures that the category_id from the request exists in the id column of the categories table. This prevents us from creating "orphan" posts that belong to a non-existent category.

The regex Rule

Sometimes, you need to enforce a very specific format for a piece of data. This is where regular expressions, or regex, come to the rescue. They are a powerful way to define patterns for strings.

Scenario: Let's say we have a field for a username, and we want it to only contain lowercase letters, numbers, and underscores.

php
'username' => 'required|regex:/^[a-z0-9_]+$/',

This regex pattern /^[a-z0-9_]+$/ ensures that the username consists of one or more lowercase letters, numbers, or underscores. No spaces, no uppercase letters, no funny business!


3. Customizing Error Messages and Attributes 📣

Laravel's default validation error messages are pretty good, but sometimes you want to make them more user-friendly or specific to your application's tone.

The Problem: The default error message for a required field might be "The title field is required." This is fine, but what if we want to add a little more personality?

The Solution: We can customize the error messages directly within our Form Request class by adding a messages method.

php
// app/Http/Requests/StoreBlogPostRequest.php

public function messages(): array
{
    return [
        'title.required' => 'Come on, every great story needs a title!',
        'body.required' => 'A post without a body is like a pizza without cheese. 🍕',
    ];
}

Now, when validation fails, our users will see these much friendlier messages.

We can also customize the attribute names used in the error messages. For example, if you have a form input named email_address, the default error message might say "The email_address field must be a valid email address." That's not very elegant. Let's fix it by adding an attributes method.

php
// app/Http/Requests/YourFormRequest.php

public function attributes(): array
{
    return [
        'email_address' => 'email address',
    ];
}

Now the error message will be much cleaner: "The email address field must be a valid email address."


4. Handling Authorization within Form Requests 🛡️

Remember that authorize method we skipped earlier? It's time to give it the attention it deserves. This method is a fantastic place to put your authorization logic. It determines if the currently authenticated user has the permission to perform the action they are requesting.

The Problem: Anyone could potentially send a POST request to our posts/store endpoint. We want to ensure that only logged-in users who have the permission to create posts can actually do so.

The Solution: We can use the authorize method to check the user's permissions. This method should return true if the user is authorized and false if they are not.

php
// app/Http/Requests/StoreBlogPostRequest.php

use Illuminate\Support\Facades\Auth;

public function authorize(): bool
{
    // Only allow logged-in users to create posts.
    return Auth::check();
}

If the authorize method returns false, Laravel will automatically generate a 403 Forbidden response, and your controller method will never even be executed. This is a simple and effective way to protect your routes.

You can also get more granular with your authorization. For example, when updating a post, you'd want to make sure that the user editing the post is the one who created it.

php
// app/Http/Requests/UpdateBlogPostRequest.php

public function authorize(): bool
{
    $post = $this->route('post'); // Get the post from the route
    return $this->user()->can('update', $post);
}

In this example, we're using Laravel's policies to check if the user has the update permission for the given $post.

By combining authorization with validation in a single Form Request class, you create a robust and secure barrier for your application's data.


Further Reading 📚

Challenge

You have been tasked with creating a robust Form Request to handle user profile updates in a Laravel application. Create a Form Request class named UpdateUserProfileRequest.

This request class must perform the following actions:

1. Authorization:

  • Implement the authorize() method.
  • It should ensure that the currently authenticated user is the same user whose profile is being updated. You can access the user model from the route using $this->route('user').

2. Validation Rules:

  • Implement the rules() method with the following validation rules:
    • name: Must be required, a string, and have a maximum of 100 characters.
    • username: Must be required, a string, and adhere to a regex pattern that only allows lowercase letters, numbers, and underscores (_). It must also be unique in the users table, but ignore the ID of the user currently being updated.
    • email: Must be required, a valid email format, and unique in the users table, ignoring the ID of the user currently being updated.
    • primary_category_id: Must be required and must exist in the id column of the categories table.
    • password: Is not required (nullable), but if present, it must be a string, have a minimum of 8 characters, and be confirmed (i.e., a password_confirmation field must also be present and match).

3. Customization:

  • Implement the messages() method to provide a custom error message for the username.regex rule: "The username can only contain lowercase letters, numbers, and underscores."
  • Implement the attributes() method to change the display name of primary_category_id to "primary category" in any validation error messages.

Expected result

Your final code should be a complete PHP class UpdateUserProfileRequest that correctly implements all the specified authorization, validation, and customization logic.

php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class UpdateUserProfileRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // Check if the authenticated user's ID matches the ID of the user from the route
        return Auth::id() === $this->route('user')->id;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $userId = $this->route('user')->id;

        return [
            'name' => 'required|string|max:100',
            'username' => [
                'required',
                'string',
                'regex:/^[a-z0-9_]+$/',
                Rule::unique('users')->ignore($userId),
            ],
            'email' => [
                'required',
                'email',
                Rule::unique('users')->ignore($userId),
            ],
            'primary_category_id' => 'required|exists:categories,id',
            'password' => 'nullable|string|min:8|confirmed',
        ];
    }

    /**
     * Get the custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'username.regex' => 'The username can only contain lowercase letters, numbers, and underscores.',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'primary_category_id' => 'primary category',
        ];
    }
}
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.