Categories: Laravel

Revamp Your Laravel Validation with prepareForValidation 3 Examples

Revamp Your Laravel Validation with prepareForValidation 3 Examples

Table of Contents

Laravel is a powerful PHP framework that simplifies web development. One of the many features that make Laravel stand out is the Form Request feature. Form Requests allow you to validate user input in a central location and prevent repetitive code in your application.

Before we dive into the examples of using prepareForValidation to revamp your Laravel validation, it’s important to note that you’ll need to create a custom form request class to take full advantage of this feature.

If you’re not familiar with creating custom form request classes in Laravel, don’t worry — we’ve got you covered! Check out our previous blog post, “Boost Laravel Form Validation with Custom Form Request Classes” for a step-by-step guide on how to create and use these classes.

Once you’ve got your custom form request class set up, you’ll be able to use the prepareForValidation method to manipulate your incoming request data before validation occurs.

One of the methods that you can use in Laravel Form Requests is the prepareForValidation method. This method is called before validation occurs, allowing you to modify the input data before it is validated. Here are three examples of how you can use the prepareForValidation method in Laravel Form Requests.

Example 1: Bcrypt Password

When a user registers on your website, they usually provide a password. To keep the password secure, it is recommended to hash it using the bcrypt algorithm. You can use the prepareForValidation method to hash the password before it is validated.

    
      'required|string|max:255',
            'email' => 'required|string|email|unique:users|max:255',
            'password' => 'required|string|min:8|confirmed',
        ];
    }

    public function prepareForValidation()
    {
        $this->merge([
            'password' => Hash::make($this->password)
        ]);
    }
}
    
   

In the above example, we are creating a RegisterUserRequest class that extends the FormRequest class. The rules method defines the validation rules for the request. The prepareForValidation method modifies the user-provided password by hashing it using the Hash::make method. This ensures that the password is securely hashed before it is validated.

Example 2: Contact Format Change

Sometimes, users might enter their contact details in different formats. For example, they might enter their phone number with or without dashes. You can use the prepareForValidation method to standardize the contact format before it is validated.

    
      'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'phone_number' => 'required|string|max:20',
        ];
    }

    public function prepareForValidation()
    {
        $this->merge([
            'phone_number' => preg_replace('/[^0-9]/', '', $this->phone_number)
        ]);
    }
}
    
   

In the above example, we are creating a ContactRequest class that extends the FormRequest class. The rules method defines the validation rules for the request. The prepareForValidation method modifies the user-provided phone number by removing all non-numeric characters using a regular expression. This ensures that the phone number is standardized before it is validated.

Example 3: Prepare Slug from Title

When creating a blog post, you might want to automatically generate a slug from the post title. This can be useful for creating SEO-friendly URLs. You can use the prepareForValidation method to generate the slug before it is validated.

    
      'required|string|max:255',
            'content' => 'required|string',
            'category_id' => 'required|exists:categories,id',
            'slug' => 'required|string|unique:posts|max:255',
        ];
    }

    public function prepareForValidation()
    {
        $this->merge([
            'slug' => Str::slug($this->title)
        ]);
    }
}
    
   

In the above example, we are creating a CreatePostRequest class that extends the FormRequest class. The rules method defines the validation rules for the request. The prepareForValidation method modifies the user-provided slug by generating a URL-friendly version of the post title using the Str::slug method. This ensures that the slug is always in the correct format before it is validated.

Conclusion

In conclusion, the prepareForValidation method in Laravel Form Requests is a powerful tool that can help you modify user input before it is validated. The three examples above show how you can use this method to hash passwords, standardize contact formats, and generate slugs from titles. By using this method, you can simplify your validation code and improve the security and usability of your application.

Popular Post

Recent Posts

Cleaning Up Your Data: Filtering Queries via Intermediate Table Columns in Laravel!

Table of Contents In Laravel, many-to-many relationships are established using an intermediate table that holds…

2 years ago

Products CRUD Example In Laravel 10 Industry Best Practice

Table of Contents Introduction: Laravel is a PHP framework that has become quite popular in…

2 years ago

Mastering the Model Lifecycle in Laravel A Comprehensive Guide

Table of Contents In Laravel, models are the backbone of the application. They act as…

2 years ago

Efficient Database Operations in Laravel with Model Scopes Global and Local Scopes Examples

Table of Contents Laravel is a popular PHP framework that is widely used for web…

2 years ago

Streamline Your Laravel Development with Route Model Binding A Real-Life Example

Table of Contents Laravel is a popular PHP framework that makes it easy to build…

2 years ago

Generating Language-Specific Catchphrases with Faker in PHP A Comprehensive Guide

Table of Contents Introduction: In software development, we often need to generate fake or mock…

2 years ago