dwightwatson / validating

Automatically validating Eloquent models for Laravel
MIT License
968 stars 76 forks source link

Add withValidator() to support conditional validation rules. #231

Closed likemusic closed 3 years ago

dwightwatson commented 3 years ago

Hi Valerij, thanks for this. Would you mind just explaining the use-case for this/how it would be used? I'd like to understand it a bit better before merging.

likemusic commented 3 years ago

@dwightwatson It's required when domain object has complex validation rules when rules for one attribute depends on other attribute's values.

More details in docs: Complex Conditional Validation

Something like this:

class CashbookItem extends BaseModel
{
    protected function withValidator($validator)
    {
        $validator->sometimes(ManualCashbookItemRequestKeysEnum::TOTAL_AMOUNT, 'gt:0', function ($input) {
            return $input[ManualCashbookItemRequestKeysEnum::TYPE_ID] === CashbookItemTypeIdsEnum::INCOME;
        });

        $validator->sometimes(ManualCashbookItemRequestKeysEnum::TOTAL_AMOUNT, 'lte:0', function ($input) {
            return $input[ManualCashbookItemRequestKeysEnum::TYPE_ID] === CashbookItemTypeIdsEnum::OUTCOME;
        });
    }
}
dwightwatson commented 3 years ago

Awesome, thanks. I've tagged 6.1.1.