Part #1: Closure-based Custom Laravel Validation

Harish Kumar · · 3944 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:

Laravel Facades: Simplifying Code and Improve Readability

As an integral part of Laravel, a renowned PHP framework, Facades provide a static interface to classes stored in the application's service container. They serve as static proxies (...)
Harish Kumar

What is Laravel’s Service Container and How to Use Dependency Injection in Laravel App

Dependency injection and inversion of control are vital in clean web development. They make writing maintainable, testable code possible. Laravel is a famous PHP framework that (...)
Harish Kumar

Secure Your SPA with Laravel Sanctum: A Step-by-Step Guide

In today's web development landscape, Single Page Applications (SPAs) are increasingly popular. But securing their interaction with backend APIs is crucial. Laravel Sanctum provides (...)
Harish Kumar

Multi-Authentication with Guards in Laravel

Laravel's robust authentication system provides a powerful mechanism for securing your application. To cater to scenarios where you need different user roles with distinct login (...)
Harish Kumar

Laravel Pint & VS Code: Automate Your Code Formatting

Laravel Pint is an opinionated PHP code style fixer built on top of PHP-CS-Fixer, designed to simplify the process of ensuring clean and consistent code style in Laravel projects. (...)
Harish Kumar

Laravel Clockwork: A Deep Dive into Debugging, Profiling Skills and Best Practices

In the world of web development, building complex applications often comes with the challenge of identifying and resolving performance bottlenecks. This is where a reliable debugging (...)
Harish Kumar