Conditional validation if checkbox selected laravel
You could do the following in this example:
public function rules(Request $request)
{
if($request->has('updatepasswordcheck'))
{
$rules['oldpassword'] = 'required';
$rules['newpassword'] = 'required';
$rules['newpasswordconfirm'] = 'required';
}
$rules['name'] = 'required|min:3';
$rules['email'] = 'required|email';
return $rules;
}
I'm using Laravel 5.5 and this code works fine, my scenario was if "Company Info" drop-down selected "Yes" then "Company Name" should be required.
Controller:
protected function validator(array $data)
{
return Validator::make($data, [
'company_name' => 'required_if:is_company,1',
]);
}
View:
<label class="control-label">Company Info</label>
<select id="is_company" class="form-control" name="is_company">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
<label class="control-label">Company Name</label>
<input type="text" class="form-control" name="company_name">
More Detail
Ok I worked it out. I did this and it works:
public function rules()
{
if($this->has('updatepasswordcheck'))
{
$rules['oldpassword'] = 'required';
$rules['newpassword'] = 'required';
$rules['newpasswordconfirm'] = 'required';
}
$rules['name'] = 'required|min:3';
$rules['email'] = 'required|email';
return $rules;
}