Laravel

Laravel 10 Validation With Example

in this article, we will explore the various ways of validating in Laravel with examples. We will create a custom rule and use it to validate input. The Laravel provides several different approaches to validate your application’s incoming data.

Laravel Framework

Laravel is an open-source PHP web application framework that is used for developing web applications and websites. It was created by Taylor Otwell and was first released in 2011.

It is widely used in web development for building various applications, from simple websites to complex web applications.

What’s Validation Rules:

Laravel offers a comprehensive set of data validation rules, which can be customized or leveraged from Laravel’s built-in rules. Laravel’s validation system is rule-based, allowing you to specify rules for each field.

The common rules are "required," "email," and "numeric“.

You can use Laravel’s inbuilt validate method for all incoming HTTP requests. This method serves to check whether the specified rules are satisfied, proceeding with the next steps, or displaying an error message in case of rule violation.

You can get all pre-defined rules from Laravel rules.

Validation Rules in Single String

You can define all rules for each field in a single string:

$validated = $request->validate([
        'employee_name' => 'required|unique:posts|max:255',
        'dept' => 'required',
    ]);

Validation Rules in Arrays

You can also define validation as arrays of rules instead of using a single string separated by '|'.

$validatedData = $request->validate([
    'employee_name' => ['required', 'unique:posts', 'max:255'],
    'dept' => ['required'],
]);

Stopping On First Validation Failure

Sometimes, We need to stop the validation process if the initial rule fails. Laravel offers the 'bail' rule for this purpose, ensuring that validation stops if any preceding validation fails.

$request->validate([
    'employee_name' => 'bail|required|unique:posts|max:255',
    'dept' => 'required',
]);

How to Validate Nested Data in Laravel

We can also define nested data in validation. You may specify these fields in your validation rules using “dot” syntax:

$request->validate([
    'employee_name' => 'required|unique:posts|max:255',
    'dept_details.name' => 'required',
    'dept_details.id' => 'required',
]);

How To Display The Validation Errors Message

Let’s display the error message when validation fails. Laravel provides $errors variable is made available to all views within your application through the 'Middleware\ShareErrorsFromSession' middleware, which is included in the web middleware group.

It’s part of web middleware so it is available on Laravel Blade template view:

Related Post
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Creating Custom Validation Rules

We have used 'validation' method to define validation rules for incoming requests. Let’s add our custom validation rules to this method. Create a ‘lowercase’ rule and attach to the validation method. This rule will be responsible for ensuring the employee_name is lowercase.

We need to register our custom validation rule in the AppServiceProvider.

Create a lowercase rule by using the following command:

php artisan make:rule LowerCase

This command creates a LowerCase file in the app/Rules folder.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class LowerCase implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */    public function passes($attribute, $value)
    {
        //
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */    public function message()
    {
        return 'The validation error message.';
    }
}

In the above file, we have two main methods:

passes()– We’ll write logic here to validate the string in lowercase.
message()– This method will display the error message if the rule is failed.

Updated file:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class LowerCase implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */    public function passes($attribute, $value)
    {
        return preg_match('/^[a-z]+$/', $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */    public function message()
    {
        return 'The :attribute must contain only lowercase letters.';
    }
}

We have defined regex to validate input values in lowercase. The error message for this custom rule is defined in the message() method

Now, We can use our custom validation rule in a controller method or in a form request.

use App\Rules\LowerCase;

// Inside a controller method or form request
public function store(Request $request)
{
    $validatedData = $request->validate([
        'employee_name' => ['required', new LowerCase],
    ]);

    // Rest of your code
}

In the above code, the 'employee_name' field is validated using the Lowercase rule, which ensures that it contains only lowercase letters.

Let’s register our custom validation rule in the AppServiceProvider. We can do this in the boot method using the Validator::extend method.

// Inside the AppServiceProvider's boot method
use Validator;

Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
    // Define your custom validation logic here
    return true; // Return true if validation passes, false otherwise
});

Conclusion:

We have learned how to use simple validation methods in your Laravel application, We have also defined inbuilt rules as well as created custom validation rules. You can also display error messages using middleware in your view file.

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories