Laravel update model with unique validation rule for attribute

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

    Append the id of the instance currently being updated to the validator.

    1. Pass the id of your instance to ignore the unique validator.

    2. In the validator, use a parameter to detect if you are updating or creating the resource.

    If updating, force the unique rule to ignore a given id:

    //rules
    'email' => 'unique:users,email_address,' . $userId,
    

    If creating, proceed as usual:

    //rules
    'email' => 'unique:users,email_address',
    

提交回复
热议问题