Part #3: Rule objects based custom validation in Laravel

Harish Kumar · · 3828 Views

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:

  1. #1: Closure-based Laravel Validation. 

  2. #2: How to use Laravel's Validator::extend method for custom validation

In this video, I will show you how you can create custom validation using Rule objects. 

Rule objects are classes that implement the Illuminate\Contracts\Validation\Rule interface. This class contains two methods: passes and message. The passes method gets the attribute value and name, and it should return true or false relying upon regardless of whether the attribute value is valid or not. The message method should return the validation error message which is used when validation fails.

To generate a new rule class, you may use the make:rule Artisan command.

php artisan make:rule MatchCurrentPassword

It will generate a MatchCurrentPassword rule object in the app/Rules directory.

Here’s what a typical custom validation rule class looks like:

<?php

namespace App\Rules;

use App\Models\User;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash;

class MatchCurrentPassword implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return Hash::check($value, $this->user->password);
    }

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

When the Rule class has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules like so.

use App\Rules\MatchCurrentPassword;

$request->validate([
    'current_password' => [
        'required',
        new MatchCurrentPassword($user)
    ],
]);

That is how you can implement your own custom rule objects that validate form requests as per your requirements.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar