So in a Request we have some validation, where the type field will be review, which means the body field has to have a minimum of 6 characters.
public function rules(){
return [
'type' => 'required|in:star_rating,review',
'body' => 'required_if:type,review|min:6'
];
}
However, the issue is that when the type is star_rating, I get an error that The body must be at least 6 characters.
This should not happen, since the body is optional and ONLY should be required and validated with min:6 if type is review. I can't seem to figure out why it runs the min:6 validation on it even if the type is star_rating.
Any idea how to get it to work as intended?
Without seeing more of your logic, I can't be certain how you want to proceed. But the concept below should get you going.
It conditionally adds rules according to parameters you define. In your case, it only requires body if type is review, and also applies the min rule of 6 characters if again, type is review.
use Validator;
// Static rules that don't change
$v = Validator::make($data, [
'type' => 'required|in:star_rating,review'
]);
// Conditional rules that do change
$v->sometimes('body', 'required|min:6', function ($input) {
return $input->type === 'review';
});
// Validator failed? Return back with errors/input
if ($validator->fails()) {
return back()->withErrors($validator)
->withInput();
}
// Proceed however you'd like with request
I had the same issue, and CamelCase's answer works well !
But I had to put my validation logic back to my controller as my attempt was to put this validation logic in a Request.
So here's another solution with conditionnal rules in the Request that works in Laravel 5.4
public function rules()
{
// general rules
$rules = [
'type' => 'required|in:star_rating,review',
];
// conditional rules
if($this->input('type') == 'review'){
$rules['body'] = 'required | min:6';
}
return $rules;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With