Member-only story

Laravel SoftDelete: Avoiding the Unique Constraint Problem

Tackling Duplicate Constraints in Laravel with SoftDelete

--

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) {
$table->string('email')->unique();
$table->softDeletes();
});

If you soft delete a user with the email johncena@wwe.com and then later create a new user with the same email, Laravel will complain about the unique constraint on the email field, throwing an error. In the same situation, when you try to restore the deleted user, Laravel also will complain about the unique constraint on the email field and throwing an same error.

This becomes a headache, especially when dealing with large systems where record restoration is a common task.

To prevent this, we can temporarily alter the values of unique fields when a record is soft deleted and restore the original values when the record is brought back. This way, the database doesn’t trip over the unique constraint during soft deletes or restores.

The Solution: Using a Trait to Avoid Duplicate Constraints

--

--

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