Part #1: Closure-based Custom Laravel Validation

Harish Kumar · · 4778 Views

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between closure-based validation and other validation methods. So, this article shows you how to use Laravel validating from request using closures.

If you only need the functionality of a custom validation rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails. Below is the code example:

$request->validate([
    'new_password' => ['required', 'min:8', 'confirmed'],
    'new_password_confirmation' => ['required'],
    'current_password' => [
        'required',

        // closure-based Validation
        function ($attribute, $value, $fail) use ($user) {
            if (! Hash::check($value, $user->password)) {
                $fail("Invalid current password.");
            }
        }
    ]
]);
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