Monday, February 27, 2017

[SOLVED]Laravel Validation Arrays - Sometimes Ignore field if another field exists in an array

I'm writing some validation rules for a Laravel application and I need to ignore some fields if another field is present. I know that the "sometimes" functionality is probably the best way to go, but how to implement the functionality with an array?
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

Advertisement