Search code examples
phplaravellaravel-validationlaravel-5.7

Laravel - Is it possible to use a validation rule on a group of attributes?


I'm using Laravel rules and I want to make a validation which requires multiple attributes. For example, I want a rule to check that the quantity requested doesn't exceed the available stock for the given product. So, something like

public function rule() {
  return [
    'quantity produyctId' => "checkQty"
}

I would prefer to solve it using rules but other methods are also acceptable.


Solution

  • You can create a custom validation from extending the validation.

    In AppServiceProvider class

    Validator::extend('quantity_validity', function ($attribute, $value, $parameters, $validator) {
    
        $productId = $parameters[0];
        $quantity = $value;
    
        // you can do whatever with these,
        // and finally return true or false according to your desire.
    });
    

    In Validation

    public function rule() {
        return [
            'quantity' => "quantity_validity:{$productId}"
        ]
    }