Laravel Validation with Soft Deleted Model and Unique DB field Laravel Validation with Soft Deleted Model and Unique DB field database database

Laravel Validation with Soft Deleted Model and Unique DB field


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')]


For updating you can adjust your validation rules to ignore the current user record when updating. The rule signature is this:

'email' => 'unique:user,email,{$userId},id,deleted_at,NULL'

For inserting new, a rule like this:

'email' => 'unique:user,email,NULL,NULL,deleted_at,NULL'

Should work and ignore softDeleted records. If will still fail if you have a unique key on your database.

Of course, if you also undelete a record, you will have duplicates, which Laravel can not prevent.


For Laravel 8, the above solutions doesn't work anymore, probably the unique rule was changed down the road.

However, you can go with the following validation rule.

use Illuminate\Validation\Rule;'email' => [    'required',    'email',    Rule::unique('users', 'email')->where(function($query){       return $query->whereNull('deleted_at')         ->orWhereNotNull('deleted_at');    })]