Search code examples
laravelvalidationunique

Laravel form request validation on store and update use same validation


I create laravel form validation request and have unique rules on that validation.

I want use it on store and update method without create new form request validation again.

but the problem is when on store the id doesnt exist and the validate is passed and when on update i failed the pass the validating because the id is exist on storage

i want to ignore the id on unique rules but use same form validate request

what is best practice to check on form validate request class if this action from store or update method to ignore unique id ?


Solution

  • Ok.. i can do it like @porloscerros Ψ suggest

        public function rules()
        {
            $rules = [
                'name' => 'required|string|unique:products|max:255',
            ];
    
            if (in_array($this->method(), ['PUT', 'PATCH'])) {
                $product = $this->route()->parameter('product');
    
                $rules['name'] = [
                    'required',
                    'string',
                    'max:255',
                    Rule::unique('loan_products')->ignore($product),
                ];
            }
    
            return $rules;
        }