0

I have created a FormRequest class with required and unique validation. Can I use the same FormRequest class for both store and update function with different validation

While Store condition should be

public function rules()
{
    
return 
[
  "name" => "required|unique:brands"
];

}

While updating condition should be (Have to ignore the current row record)

public function rules()
{
    
return 
[
 "name" => "required|unique:brands,id,".$this->id
];

}
ManiMuthuPandi
  • 1,594
  • 2
  • 26
  • 46
  • 2
    this question answers yours [Laravel form request validation on store and update use same validation](https://stackoverflow.com/questions/61543013/laravel-form-request-validation-on-store-and-update-use-same-validation) – bhucho Nov 26 '20 at 09:41
  • 1
    Does this answer your question? [Laravel form request validation on store and update use same validation](https://stackoverflow.com/questions/61543013/laravel-form-request-validation-on-store-and-update-use-same-validation) – Harpal Singh Nov 26 '20 at 10:11

2 Answers2

2

Thank you @bhucho and @Harpal Singh for the links. Based on the answer provided on the question, I found answer for my question.

public function rules()
{
    $rule = ["name" => "required|unique:brands"];
    
    if (in_array($this->method(), ['PUT', 'PATCH']))
        $rule["name"].= ",id,".$this->id;
    
    return $rule;
}
ManiMuthuPandi
  • 1,594
  • 2
  • 26
  • 46
0

You can use this format

return ["name" => "required|unique:brands,name,".$this->id];

parth
  • 1
  • I want the validation for both condition. For add and update. your code will work for update. I have found solutions from the comment links and added the answer – ManiMuthuPandi Nov 26 '20 at 10:28