Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ethar's avatar
Level 5

unique validation with soft delete

i have this validation rule for phone number

'mobile' => 'required|min:9|max:15|unique:users',

but I use soft delete and want to allow user to register with the same number of deleted_at not null I try this

'mobile' => 'required|min:9|max:15|unique:users,deleted_at,NULL',

but not working

0 likes
8 replies
tykus's avatar

Just use the Rule class:

Rule::unique('users')->whereNull('deleted_at')

The string rule you need is a PITA - you need to specify the column, 2 NULLs for the ignore rule, and only then specify extra where's!

unique:users,mobile,NULL,NULL,deleted_at,NULL
2 likes
ethar's avatar
ethar
OP
Best Answer
Level 5

@tykus i change to use rule

 'mobile' => ['required','min:9','max:15', Rule::unique('users')->whereNull('deleted_at')],

but same error

Duplicate entry '0566666666' for key 'users.users_mobile_unique'
Yorki's avatar

@ethar thats because you have unique index on mobile column which doesn't care about other columns like deleted_at

1 like
tykus's avatar

@ethar is that a trashed record; because while your validation rule explicitly excludes soft-deleted records, the database's UNIQUE index is ignorant of soft-deletes as a concept!

2 likes
tykus's avatar

@ethar well, that depends on the business logic; but it seems you want the trashed record and a new one with the same mobile, so UNIQUE might not be appropriate on the database, but can still be enforced with validation rule.

1 like
Garet's avatar

@ethar Generally I think this is a bad idea. Because when you restore that soft delete (which is surely the idea behind using soft deletes - the fact that you can restore the record if you need to), you're going to end up with two records that have the same value.

technoigniters's avatar

For storing/adding record in database 'email' => 'required|email|unique:users,email,NULL,id,deleted_at,NULL',

For updating/editing record in database 'email' => 'required|email|unique:users,email,'.$id.',id,deleted_at,NULL', Here $id is record id of particular editing user in user table.

Please or to participate in this conversation.