unique validation on soft-deleted records
Hi experts,
I have a simple form for users. The email address should be unique. The users Model uses soft-deletes.
The formfield for email looks like this:
TextInput::make('email')
->rules(['required', 'email'])
->unique( ignoreRecord: true )
->placeholder('Email')
This all works fine until I delete a user and want to create a new user with the same email as the deleted user.
In plain Laravel controller I could do something like: 'email' => 'unique:user,email,{$userId},id,deleted_at,NULL'
What would be the equivalent in my filament form?
Thx for help!6 Replies
You can do the same thing in the rules() method for the field.
Thx for your answer! But where do I get the id of the current userrecord then?
Not sure, exactly. Maybe something like the below could be helpful. Seems odd though to not apply unique to soft deletes too, since they are still technically a valid record. What happens if you do this, then the soft deleted model is restored? You won't be able to restore it because that email will already exist in the DB and the DB validation will fail.
Thx for your help. Unfortunately your solution did not work, but I solved myself. It's actually much easier (as I was expcting from filament :))
->unique( ignoreRecord: true, callback: function( Unique $rule ){
return $rule->whereNull('deleted_at');
} )
is all that is needed.I'm getting this error? @low-res (Paul)
This works for me