This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Secure Any CMS With Ease with Our Malware Protection Add-On! LEARN MORE→

How to Create and Apply Validation Rules in Laravel

Updated on December 1, 2024

6 Min Read
laravel validation

Ever had trouble checking user data in your web apps? It’s important to make sure this data is correct, safe, and useful. But, setting up good validation rules can be tough, especially with complex forms and data.

What if there was an easier way? Laravel has a strong validation system. It makes it easy to set up and use validation rules. With Laravel, you don’t need to write long validation code to keep your app’s data in check.

So, how can you use Laravel’s validation system? This blog post will guide you. It has step-by-step instructions, code examples, and practical tips. Whether you’re new to Laravel or an experienced developer, this blog is for you.

Why Is Data Validation Important?

Data validation makes sure data is correct and trustworthy.

This is a key because decisions based on wrong data can be costly. Data checking stops errors from getting into the data system. It saves time and makes sure other processes that use this data are not messed up.

It also makes data consistent using set rules for data format and structure. This is important when dealing with lots of data or when many people are using the data. Consistent data makes it easier for teams to work together.

Consider the example of an ecommerce store.

When customers place an order, they provide information such as their name, address, and payment details. If this data is not validated, incorrect information could lead to failed transactions, delivery to the wrong address, or even security issues.

Hence, data validation is crucial to ensure the smooth operation of the store and customer satisfaction.

Validation Rules in Laravel

When making web apps with Laravel, it’s important to make sure user inputs are correct. Laravel makes this easy with its checking system. Knowing the different checking rules helps you make sure the data is correct.

Laravel’s checking rules cover many situations. Here are some key rules:

Rules Description
required Ensures the field is present in the input data.
numeric Validates that the input is a numeric value.
email Checks if the input is a valid email address.
alpha Verifies that the input contains only alphabetic characters.
min Specifies the minimum value allowed for numeric input.
max Sets the maximum value allowed for numeric input.
unique Ensures the input value is unique in a specified database table.
confirmed Matches the input value with a confirmation field.

Apply Validation Rules

It’s a simple process that involves leveraging the validation functionality provided by the framework. Below is a basic example of applying validation rules within a controller:

public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users',
        'password' => 'required|string|min:8|confirmed',
    ]);

    // Process the validated data
}

Set up Laravel for Data Validation

Add Rules Conditionally

In real-world scenarios, you may need to apply validation rules based on certain conditions. Laravel enables you to conditionally add rules to your validation process.

$rules = [
    'name' => 'required|string|max:255',
    'email' => 'required|email',
];
if ($someCondition) {
    $rules['additional_field'] = 'required|string';
}
$request->validate($rules);

Unlock Laravel Power: Easy Validation, Zero Server Pains

Simplify your workflows, ditch server management, and focus on building. Cloudways makes Laravel validation a breeze.

Advanced Validation Rules

When websites get more complex, we need better ways to check data. Laravel helps us do this with its strong checking system. Let’s see how you can make your checks better.

Custom Rules

Laravel lets you make your own checks that fit your website’s needs. You can add these to your AppServiceProvider’s boot method.

use Illuminate\Support\Facades\Validator;

Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
    // Your custom validation logic here
    return $value == 'custom_value';
});

You can use this custom validation like any other.

$request->validate([
    'custom_field' => 'custom_rule',
]);

Rule Objects

Laravel 10 brought in Rule objects. These let you organize your checks better. You can make a Rule object by using the Illuminate\Contracts\Validation\Rule interface.

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{
    public function passes($attribute, $value)
    {
        // Your validation logic here
        return $value == 'custom_value';
    }

    public function message()
    {
        return 'The validation failed for this custom rule.';
    }
}

You can use this Rule object when you validate data.

$request->validate([
    'custom_field' => [new CustomRule],
]);

Use Advanced Validation Rules

Using Rule objects makes your data cleaner. You can make advanced validation by using multiple Rule objects.

use App\Rules\CustomRule1;
use App\Rules\CustomRule2;

$request->validate([
    'field1' => [new CustomRule1, new CustomRule2],
    'field2' => ['required', new CustomRule1],
]);

Inline Custom Validation Messages

You can give custom error messages when you validate data. This is useful when the default messages aren’t specific enough:

$request->validate([
    'field' => 'required|numeric|between:1,10',
], [
    'field.between' => 'The :attribute must be between 1 and 10.',
]);

Custom Validation Rules

Custom validation rules in Laravel let web developers make checks that fit their websites. These checks can handle unique data needs or business logic checks. Let’s see how to make and use custom check rules in Laravel.

One way to make custom check rules is by adding to Laravel’s Validator. In your AppServiceProvider, inside the boot method, you can use the extend method to add a custom rule.

use Illuminate\Support\Facades\Validator;

Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
    // Your custom validation logic here
    return $value == 'desired_value';
});

Now, you can use this custom rule when you validate data:

$request->validate([
    'custom_field' => 'custom_rule',
]);

Use Custom Validation Rules

Inline Custom Validation Messages

You can also give custom error messages for better understanding:

$request->validate([
    'field' => 'required|numeric|custom_rule',
], [
    'field.custom_rule' => 'The :attribute must meet the custom validation criteria.',
]);

Conditional Usage

Custom validation rules are very useful when dealing with conditional checks. You can use rules based on specific situations:

$request->validate([
    'field1' => 'required|numeric|custom_rule_if:other_field,value',
    'field2' => 'required|custom_rule_unless:another_field,value',
]);

Form Request Validation

Form Request Validation allows you to centralize the validation logic for a specific HTTP request. Instead of cluttering your controllers with validation rules, you can create dedicated Form Request classes, keeping your code organized and easy to maintain.

Create Form Request Classes

Step 1: Generate Form Request Classes

To create a Form Request class, you can use Laravel’s artisan command-line tool:

php artisan make:request MyFormRequest

This command will generate a new Form Request class in the App\Http\Requests directory. Open the generated file, and you’ll find a rules method where you can define your validation rules.

public function rules()
{
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users',
        // Add more rules as needed
    ];
}

Step 2: Create Form Requests in Controller

Now that you’ve created your Form Request class, you can use it in your controller method:

use App\Http\Requests\MyFormRequest;

public function store(MyFormRequest $request)
{
    // The request has already been validated at this point
    // Your business logic goes here
}

Laravel automatically validates the incoming request using the rules defined in your Form Request class before reaching your controller method.

Authorize Form Requests

Form Requests not only handle validation but also provide a convenient way to authorize the incoming request. You can define an authorize method in your Form Request class:

public function authorize()
{
    // Return true or false based on authorization logic
    return $user->can('create', Post::class);
}

If the authorize method returns false, Laravel will automatically abort the request with a 403 Forbidden response.

Customize Error Messages

Form Requests make it easy to customize error messages. You can override the messages method in your Form Request class:

public function messages()
{
    return [
        'name.required' => 'The name field is required.',
        'email.unique' => 'The email address must be unique.',
        // Add more custom messages as needed
    ];
}

Handle Validation Redirects

When a Form Request validation fails, Laravel will automatically redirect back to the previous page with the validation errors flashed to the session. This simplifies the process of informing users about validation issues.

Summary

Laravel Validation is a key tool that helps keep your data safe and correct. It checks user input before it’s used, making sure it fits the rules you set. Laravel offers many ways to check your data. But there’s more to Laravel Validation.

It also handles user permissions and lets you set custom error messages. If the checks don’t pass, Laravel smartly sends users back to the previous page with the errors. Learning about these features, including how Laravel mitigates Mass Assignment Vulnerabilities and provides robust validation, shows how Laravel gives you easy-to-use tools to build secure and reliable applications. These safeguards ensure that unauthorized data cannot be injected into your models and that all user inputs meet predefined criteria before being processed.

1. Can I create custom validation rules in Laravel?

A. Absolutely! Laravel provides a flexible system for creating custom validation rules through closures or extending existing rules. This allows you to validate data against specific constraints not covered by built-in rules.

2. How can I test my Laravel validation rules to ensure they’re working correctly?
A. Using PHPUnit test cases is a recommended approach. These tests simulate various data scenarios to verify if the rules behave as expected, handling both valid and invalid input.

3. What are the built-in validation rules provided by Laravel?
A. Laravel offers a diverse set of built-in rules like required, numeric, email, unique, and accepted. These cover common validation needs, eliminating the need for extensive custom code.

Can I validate nested array data in Laravel?
A) Yes, you can validate nested array data using dot notation. For example:

$validatedData = $request->validate([
    'address.street' => 'required|string',
    'address.city' => 'required|string',
]);

How do I validate a form in Laravel?
A) You can validate a form by using the validate() method within a controller.

$validatedData = $request->validate([
    'email' => 'required|email',
    'password' => 'required|min:8',
]);
Share your opinion in the comment section. COMMENT NOW

Share This Article

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Claim Now