Search code examples
phplaravellaravel-5laravel-validation

Laravel :values placeholder not working?


I've created a custom validator for extensions:

Validator::extend('extension', function ($attribute, $file, $extensions, $validator) {
    $ext = strtolower(@$file->getClientOriginalExtension());

    return in_array($ext, $extensions);
});

And the custom message:

'extension' => 'The :attribute must be a file of type: :values.',

It doesn't seem to replace the :values part.

I've tried using the custom replace also without luck:

Validator::replacer('wtf', function ($message, $attribute, $rule, $parameters) {
    return 'show me something!!!!!';
});

But this doesn't do anything either.

What's missing?


Solution

  • Laravel doesn't translate values placeholder by default. You did the right thing by using replacer (docs). But looks like you made some mistakes.

    A ServiceProvider code:

    // in boot method define validator
    Validator::extend('extension', function ($attribute, $file, $extensions, $validator) {
        $ext = strtolower(@$file->getClientOriginalExtension());
    
        return in_array($ext, $extensions);
    });
    // then - replacer with the same name
    Validator::replacer('extension', 
        function ($message, $attribute, $rule, $extensions) {
            return str_replace([':values'], [join(", ", $extensions)], $message);
    });
    

    In controller:

    $validator = Validator::make($request->all(), [
        'file' => 'required|extension:jpg,jpeg',
    ]);
    

    In language file:

    'extension' => 'The :attribute must be a file of type: :values.',