Part #1: Closure-based Custom Laravel Validation
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.");
}
}
]
]);
Please login or create new account to add your comment.