Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle unique validation conflicts caused by soft-deleted records #54275

Draft
wants to merge 2 commits into
base: 11.x
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Illuminate/Validation/Rules/Unique.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,23 @@ public function __toString()
$this->formatWheres()
), ',');
}

/**
* Apply a condition to exclude soft-deleted records.
*
* @param Model|null $model
* @return $this
*/
public function withSoftDeletes(?Model $model = null): static
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might want to add similar functionality to ignore(), where what is passed can be one of a few options:

public function ignore($id, $idColumn = null)
{
if ($id instanceof Model) {
return $this->ignoreModel($id, $idColumn);
}
$this->ignore = $id;
$this->idColumn = $idColumn ?? 'id';
return $this;
}

In our case, this would be either a model or the column name directly.

{
$this->where(function ($query) use ($model) {
$deletedAtColumn = $model && method_exists($model, 'getDeletedAtColumn')
? $model->getDeletedAtColumn()
: 'deleted_at';

$query->whereNull($deletedAtColumn);
});

return $this;
}
}