Laravel update model with unique validation rule for attribute

后端 未结 18 2222
春和景丽
春和景丽 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:32

    I have BaseModel class, so I needed something more generic.

    //app/BaseModel.php
    public function rules()
    {
        return $rules = [];
    }
    public function isValid($id = '')
    {
    
        $validation = Validator::make($this->attributes, $this->rules($id));
    
        if($validation->passes()) return true;
        $this->errors = $validation->messages();
        return false;
    }
    

    In user class let's suppose I need only email and name to be validated:

    //app/User.php
    //User extends BaseModel
    public function rules($id = '')
    {
        $rules = [
                    'name' => 'required|min:3',
                    'email' => 'required|email|unique:users,email',
                    'password' => 'required|alpha_num|between:6,12',
                    'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
                ];
        if(!empty($id))
        {
            $rules['email'].= ",$id";
            unset($rules['password']);
            unset($rules['password_confirmation']);
        }
    
        return $rules;
    }
    

    I tested this with phpunit and works fine.

    //tests/models/UserTest.php 
    public function testUpdateExistingUser()
    {
        $user = User::find(1);
        $result = $user->id;
        $this->assertEquals(true, $result);
        $user->name = 'test update';
        $user->email = 'ffffd@test.si';
        $user->save();
    
        $this->assertTrue($user->isValid($user->id), 'Expected to pass');
    
    }
    

    I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well. (tested on Laravel 5.0)

提交回复
热议问题