Check if name is unique among non-deleted items with Laravel validation
When managing resources in a project where data removal is handled via soft deletes, standard uniqueness constraints can quickly become a source of friction. Consider a scenario where you have a versions table storing item names for specific projects. You implement soft deletes to preserve historical audit trails but ensure that logically deleted records no longer appear in active lists.
If your form submission logic relies on the default Laravel validation rule unique:versions,name,NULL,id,project_id,$project->id, it will fail to account for those soft-deleted rows. The query generated by this validator checks every row in the table where name is null (which usually isn't the case here) or simply ignores the deletion flag entirely depending on your model configuration, effectively treating a "deleted" item as an active one. This results in a user being unable to reuse a name like 'Test' immediately after deleting their initial 'Test' entry for that project.
To resolve this, you must explicitly tell Laravel's query builder to filter out soft-deleted records within the validation rule itself. The most straightforward approach is to append an additional condition to the unique rule using the where clause syntax supported by Eloquent builders.
You can modify your validation array in the controller or request class as follows:
'rules' => [
'name' => [
'required',
'min:1',
\Illuminate\Validation\Rule::unique('versions', 'name')
->where('project_id', $project->id)
->whereNull('deleted_at'), // This filters out soft-deleted rows
],
],
By chaining the whereNull('deleted_at') method to the rule, you ensure that the uniqueness check runs against only the active records. The validator constructs a SQL query equivalent to:
SELECT * FROM versions WHERE name = ? AND project_id = ? AND deleted_at IS NULL
This approach keeps the logic contained within the validation layer without requiring changes to your database schema or migration files. It is a low-overhead solution that respects the existing soft-delete infrastructure you have already built.
However, there are trade-offs to consider with this method. While appending whereNull directly in the rule works well for simple cases, it ties validation logic to specific column names like deleted_at. If you ever decide to switch from the default trait behavior or change your soft-delete implementation (for instance, using a custom deletedAt column name), you will need to update every single validation rule across your application. This can lead to scattered configuration and potential maintenance issues if not managed carefully.
Another alternative involves defining a global scope on your model, but that is typically reserved for query scopes rather than validation scopes unless specifically configured via the scopes property in the Model. Using a global scope for this specific purpose might obscure the intent of the rule, making it less clear to other developers reading the code that this is a data integrity constraint rather than a generic query filter.
If your project grows significantly and you find yourself repeating these complex validation rules across many controllers, you might consider extracting the logic into a dedicated Request validator or a service object. This ensures consistency and makes the filtering criteria explicit in one place. For example, you could create a VersionValidator trait that accepts the column name for the deleted timestamp as an argument, allowing you to swap implementations without touching every controller file.
Ultimately, the decision depends on how rigid your soft-delete strategy is. If all your models strictly use the default deleted_at column, the inline whereNull approach offers a quick win with minimal code changes. But if your architecture varies or you anticipate frequent shifts in data retention strategies, encapsulating the logic becomes a more sustainable engineering choice.