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) {…