First attempt (didn't work, because Laravel validates any time the field is present):
// Device Rules
$deviceRules = [
'devices' => 'required|array|min:1',
'devices.*.id' => 'integer',
'devices.*.network' => 'max:255',
'devices.*.code' => "required_without:devices.*.id|max:255|unique:devices,code",
'devices.*.make_id' => 'required_without:devices.*.id|in:' . Make::getImplodedKeys(),
'devices.*.model_id' => 'required_without:devices.*.id|in:' . DeviceModel::getImplodedKeys(),
'devices.*.fault_id' => 'required|array|min:1',
'devices.*.fault_id.*' => 'in:' . Fault::getImplodedKeys(),
'devices.*.warranty' => 'required|boolean'
]
So my second attempt using 'sometimes()' (but I don't quite know how to implement this.):public function rules()
{
// Device Rules
$deviceRules = [
'devices' => 'required|array|min:1',
'devices.*.id' => 'integer',
'devices.*.network' => 'max:255',
'devices.*.fault_id' => 'required|array|min:1',
'devices.*.fault_id.*' => 'in:' . Fault::getImplodedKeys(),
'devices.*.warranty' => 'required|boolean'
];
return $deviceRules ;
}
protected function getValidatorInstance(){
$validator = parent::getValidatorInstance();
$validator->sometimes('devices.*.code', 'required|max:255|unique:devices,code', function($input)
{
return isset($input->devices.*.id);
});
$validator->sometimes('devices.*.make_id', 'required|in:' . Make::getImplodedKeys(), function($input)
{
return isset($input->devices.*.id);
});
$validator->sometimes('devices.*.model_id', 'required|in:' . DeviceModel::getImplodedKeys(), function($input)
{
return isset($input->devices.*.id);
});
return $validator;
}
I haven't tested this because obviously it won't work, return isset($input->devices.*.id);
will without doubt throw an error. How can I properly implement this?via Samyoul