I am trying to wrap my head around how to handle this use case.
I have a user model that has a unique db field (email). I am also using soft deletes.
I need to handle three cases:
1) The user model is updated. At the moment my validation stops the user from being updated, because ofcourse this email already exists. I think this is easily solved by ignoring the email validation if the email has not been changed.
2) A different user model is updated and the email is changed to another email already present in the db.
3) A new model is created and the email is already present in the db.
All the above scenarios must also take into account soft deleted models.
Would someone have some advice on how to structure this?
You can use the Rule::unique()
validation. Either get your user model out from the route if your using model binding, or do a traditional db query to get the user out by an ID (if your passing one in). Then you can do this in the validation.
This should accommodate soft deleted models too.
return [
'email' => Rule::unique('users', 'email')->ignore($user->email)->whereNull('deleted_at')->orWhereNotNull('deleted_at')
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With