1

I want to create a custom rule in Laravel 10. I used php artisan rule:make ValidPackageItem, and this class is generated

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class ValidPackageItems implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        //
    }
}

and used it in the controller

$validator = Validator::make($request->all(),
            [
                'items' => 'required|valid_package_items'
            ]
        );

while now calling this function, i get this error

App\Rules\ValidPackageItems::validate(): Argument #3 ($fail) must be of type Closure, array given

I cant even know what is the validator is passing to this custom rule to know the problem, even after i changed the

* @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail

to \Closure(array): it does not solve it, and i remove the Closure declaration and make it just $fail , it goes into the class but the Validator always throw and error message even if the data is correct

I used to use invokable rules, but its depreciated in Laravel 10

anyone know a solution ? thanks in advance

I wanted to make a custom validation rule in Laravel X10 but i got an error I expect the error to be solved and i can customize my rule

1 Answer 1

2

I got the solution guys, the problem on how you invoke with the validation call

just run php artisan rule:make ValidatePackageItems

and the class generated, after that you have to call it this way

'items' => ['required', new ValidPackageItem()]

I was registering the validation rule in the Providers/AppServiceProvider.php in the boot method, was trying to call it this way

items => 'required,valid_package_items,some_condition

as you saw, I dont really know if the problem was into registration & invoking or something else, but I got no time to try with registration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.