Laravel update model with unique validation rule for attribute

后端 未结 18 2223
春和景丽
春和景丽 2020-11-27 12:45

I have a laravel User model which has a unique validation rule on username and email. In my Repository, when I update the model, I rev

18条回答
  •  盖世英雄少女心
    2020-11-27 13:16

    Laravel 5.8 simple and easy

    you can do this all in a form request with quite nicely. . .

    first make a field by which you can pass the id (invisible) in the normal edit form. i.e.,

     

    ... Then be sure to add the Rule class to your form request like so:

    use Illuminate\Validation\Rule;
    

    ... Add the Unique rule ignoring the current id like so:

    public function rules()
    {
        return [
              'example_field_1'  => ['required', Rule::unique('example_table')->ignore($this->id)],
              'example_field_2'  => 'required',
    
        ];
    

    ... Finally type hint the form request in the update method the same as you would the store method, like so:

     public function update(ExampleValidation $request, Examle $example)
    {
        $example->example_field_1 = $request->example_field_1;
        ...
        $example->save();
    
        $message = "The aircraft was successully updated";
    
    
        return  back()->with('status', $message);
    
    
    }
    

    This way you won't repeat code unnecessarily :-)

提交回复
热议问题