Reputation: 377
I have created a custom validator in AppSeriveProvider.php
with code:-
Validator::extend('less_than', function($attribute, $value, $parameters, $validator) {
$max_field = $parameters[0];
$data = $validator->getData();
$max_value = 100;
return $value < $max_value;
});
Validator::replacer('less_than', function($message, $attribute, $rule, $parameters) {
return str_replace(':field', $parameters[0], $message);
});
And my controller have this piece of code
$messages = [
'bid.required' => 'Please enter the amount',
'bid.less_than' => 'Insufficient balance',
];
$balance = 100;
$v = Validator::make($request->all(), [
'bid' => 'required|less_than:$balance',
],$messages);
if ($v->fails()) {
return redirect('newgame')
->withErrors($v)
->withInput();
}else {
echo "Success"
}
I have to send balance variable to the validator and in the validator function I have to set $max_value (which currently have 100) to the value in $balance.
After searching in directories and looking to the code I cannot understand that what are the contents of $parameters
variable because its 0 index is referred in max_field, how $validator->getData()
works? and how $max_value
is getting its value.
Please someone explain me all this or comment the link to respective problems.And help in solving this big problem.
Upvotes: 1
Views: 4786
Reputation: 377
To solve this problem I used the laravel's function dd() to see what are the contents of each variable. And then changed the custom validator in AppSeriveProvider.php
to
Validator::extend('less_than', function($attribute, $value, $parameters, $validator) {
$balance = $parameters[0]; //$parameters array contain the $balance passed by validator::make()
$data = $validator->getData(); //$data contain the $request->all()
return $value < $balance; //$value contain the bid set by user
});
Validator::replacer('less_than', function($message, $attribute, $rule, $parameters) {
return str_replace(':field', $parameters[0], $message);
});
And the controller's code to
$messages = [
'bid.required' => 'Please enter the amount',
'bid.less_than' => 'Insufficient balance',
];
$balance = $user->balance;
$v = Validator::make($request->all(), [
'bid' => "required|less_than:$balance", //this balance variable acts as the parameter array for extended validator class
],$messages);
if ($v->fails()) {
return redirect('newgame')
->withErrors($v)
->withInput();
}else {
echo "Success";
}
Explanation is provided in comments in code.
Upvotes: 4