Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get access to value that failed validation, in a replacer?

When using a custom validation rule and replacer within Laravel, I am really struggling to find any documentation that would simply allow you to get the value that failed validation.

For example, I have created a file exists validator:

Validator::extend('view_exists', function($field,$value,$parameters) 
{
    return View::exists($value);
});
Validator::replacer('view_exists', function($message, $attribute, $rule, $parameters)
{
    return str_replace(':filename', 'THE ENTERED VALUE', $message);
});

Now, when I create a rule that is:

$rules = array('filename' => 'required|view_exists');
$messages = array('filename.view_exists' => 'Filename \':filename\' does not exist');

When I enter an invalid path, such as safsakjhdsafkljh, I was hoping it could return

Filename 'safsakjhdsafkljh' does not exist

However the replacer is not able to access the value that failed the validation. I've tried outputting all parameters that are passed to the closure, including $this and it's no where to be seen :(

Before I resort to using Input::get (urgh), am I missing something completely obvious?

Thanks

Gavin

like image 423
Gavin Avatar asked Aug 02 '14 21:08

Gavin


1 Answers

With Laravel 5.4 you can access Validator instance in replacer callback like following:

Validator::replacer('view_exists', function ($message, $attribute, $rule, $parameters, Validator $validator) {
    $value = array_get($validator->getData(), $attribute);

    return str_replace(':filename', $value, $message);
});
like image 74
Vedmant Avatar answered Oct 20 '22 00:10

Vedmant