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
awcodes
awcodes17mo ago
You can do the same thing in the rules() method for the field.
low-res (Paul)
low-res (Paul)OP17mo ago
Thx for your answer! But where do I get the id of the current userrecord then?
awcodes
awcodes17mo ago
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.
->rules([
function (Model $record) {
return function (string $attribute, $value, Closure $fail) use ($record) {
if ($value === 'foo') {
$fail("The {$attribute} is invalid.");
}
};
},
])
->rules([
function (Model $record) {
return function (string $attribute, $value, Closure $fail) use ($record) {
if ($value === 'foo') {
$fail("The {$attribute} is invalid.");
}
};
},
])
low-res (Paul)
low-res (Paul)OP17mo ago
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.
Hasith
Hasith10mo ago
I'm getting this error? @low-res (Paul)
No description
Hasith
Hasith10mo ago
This works for me
TextInput::make('email')->required()->email()->unique(modifyRuleUsing: function (Unique $rule) {
return $rule->whereNull('deleted_at');
}),
TextInput::make('email')->required()->email()->unique(modifyRuleUsing: function (Unique $rule) {
return $rule->whereNull('deleted_at');
}),
Want results from more Discord servers?
Add your server