Member-only story

Laravel SoftDelete: Avoiding the Unique Constraint Problem

Tackling Duplicate Constraints in Laravel with SoftDelete

Hafiq Iqmal
4 min readOct 6, 2024

In case you’ve been using Laravel for a while, especially when projects involve data integrity, most likely you have already encountered the SoftDelete feature. Pretty useful because you can “delete” records without really taking them out of the database. What Laravel does is just add a deleted_at timestamp so it marks it as deleted, but remains in the system. That’s all well and good to retain historical data, but it does introduce one potentially sticky problem — what happens to unique constraints when you restore soft-deleted records?

This becomes a problem when you want to restore a record that already has, for instance, a unique email or username, in the database. Laravel will just throw an error and stop the proceedings. Fortunately, there’s an easy way of avoiding this problem in a very clean manner.

Let’s walk through a solution using a trait that will help you bypass the unique constraints when using SoftDelete in Laravel.

Understanding the Problem

Let’s take a basic example. Imagine you have a users table with an email field that must be unique:

Schema::create('users', function (Blueprint $table) {…

--

--

Hafiq Iqmal
Hafiq Iqmal

Written by Hafiq Iqmal

Technical Lead | Software Engineer | Laravel Enthusiasts | Tech writer | UiTM Alumni | Husband | Proud father of a beautiful daughter

No responses yet