Search code examples
laravellaravel-validation

Laravel Validator::extendedDependent() dynamic error message


Validator::extendDependent('cbu_deposit', function ($attribute, $value, $parameters, $validator){     
             $arr = explode('.', $attribute);
             $account = $validator->getData()[$arr[0]][$arr[1]];

             $type = $account['type'];
             if($value < $type['minimum_deposit_per_transaction']){
                return false;
             }
             return true;
});

According to the laravel api the third parameter is the $message

void extendDependent(string $rule, Closure|string $extension, string|null $message = null)

I'm wondering how to make he error message dynamic like this

$error = "Mininum deposit for " .$type['product_id']. ' is : '.$type['minimum_deposit_per_transaction'].'.';

Solution

  • I have found the answer using the $validator->addReplacer() method inside Validator::extendDependent('cbu_deposit').

     $customMessage = "Mininum deposit for " .$type['product_id']. ' is : '.$type['minimum_deposit_per_transaction'].'.';
    
                $validator->addReplacer('cbu_deposit', 
                    function($message, $attribute, $rule, $parameters) use ($customMessage) {
                        return \str_replace(':custom_message', $customMessage, $message);
                    }
                );