Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation with Soft Deleted Model and Unique DB field

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?

like image 344
PiotrG Avatar asked Dec 24 '22 04:12

PiotrG


1 Answers

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')
]
like image 145
John Halsey Avatar answered Dec 25 '22 16:12

John Halsey