Data Recovery in Laravel: A Step-by-Step Guide to Laravel Soft Deletes

Chimeremze Prevail Ejimadu
5 min readOct 2, 2023

--

Photo by Devin Avery on Unsplash

Managing data is like a delicate balancing act. We often need to delete data that’s no longer needed, but what if we accidentally delete something important or need to recover data that was thought to be gone forever?

This is where the concept of “soft deletes” and managing “trashed records” comes into play. I will show you all the cool things you can do with soft delete and why you must use it.

Why Data Deletion Can Be a Challenge

When you delete data from a database, it’s usually gone for good. However, this can be problematic, especially when it comes to complying with data retention policies or handling accidental deletions. What if you need to restore deleted data for auditing purposes or customer requests?

The Role of Soft Deletes

This is where “soft deletes” come to the rescue. Soft deletes are a way to mark data as deleted rather than physically removing it from the database. Think of it as putting data into a virtual recycle bin instead of sending it to the digital shredder. This way, you can retain trashed records for as long as you need, ensuring compliance with data retention policies.

In Laravel, soft deletes are a feature that allows you to mark a record as “deleted” without actually removing it from your database. Instead of permanently erasing data, soft deletes add a special flag to the record, letting Laravel know that it’s been trashed.

Soft Deletes vs. Hard Deletes

Here’s the key difference: with a hard delete, the record is gone forever. It’s like tossing a piece of paper into a shredder — you can’t get it back. But with soft deletes, it’s more like moving that piece of paper to a “Recycle Bin” on your computer. It’s out of sight, but it’s not gone. You can still recover it.

The Real Benefits of Using Soft Deletes

Before I show you some cool things you can do with soft delete, Let’s see some reason why using soft delete is very important.

Now, why would you ever need to restore a soft-deleted record?

Real-world scenarios where record restoration comes in handy:

  1. Customer Data Recovery: Imagine a scenario where a user accidentally deletes their account. With soft deletes and record restoration, you can effortlessly recover their data, keeping your users happy.
  2. Audit Trails: Businesses often require audit trails for legal or compliance reasons. Soft deletes let you maintain historical records even when an entity has been deleted, ensuring transparency.
  3. Content Management: In content management systems, authors might accidentally delete important articles. Restoration helps preserve valuable content.
  4. User Error Mitigation: Users sometimes make mistakes, such as deleting a critical document in a document management system. Soft deletes offer a safety net.

In these scenarios, the ability to restore soft-deleted records can be a lifesaver, allowing you to recover valuable data and maintain a smooth user experience.

Implementing Soft Deletes in Laravel

Now that we understand the value of soft deletes in Laravel, let’s see how to implement them.

First, we need to add a deleted_at column to the table for the model where we want to enable soft deletes. Let's say we have a Posts table for a blogging app. Open the migration file for the model and add $table->softDeletes() to the list of columns. Look at this example

public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('title');
$table->text('description');
$table->text('post');
$table->timestamps();
$table->softDeletes(); // This adds the 'deleted_at' column
});
}

Next, In your Eloquent model (in this case, the Post model), use the SoftDeletes trait. Here's an example:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
use SoftDeletes; // Add this line to enable soft deletes

// Other model properties and methods...
}

That’s it!

With these two steps, you’ve enabled soft deletes for your Laravel model. Now, when you delete a record using Eloquent methods like delete(), Laravel will set the deleted_at timestamp, marking the record as "trashed" rather than permanently deleted.

So how can I use it?

An example will show you how. Take a look:

public function deletePost($id)
{
$post = Post::find($id);
$post->delete(); // This soft deletes the post

// Additional logic...
}

Great, it is now deleted. So what if there is need to restore the deleted data/? That’s the best part of soft deletes in laravel. Here’s how we do it.

public function restorePost($id)
{
$post = Post::withTrashed()->find($id);
$post->restore(); // This restores the soft-deleted post

// Additional logic...
}

Using withTrashed() allows you to find soft-deleted records.

Great! What if I still want to permanently delete a record?

Laravel still got you covered with the forceDelete() method.

When you call $model->forceDelete(), you're opting for a permanent delete. This method removes the record entirely from the database, including the deleted_at timestamp. It’s like tossing a piece of paper into the digital shredder; there’s no getting it back.

public function deletePostForever($id)
{
// If you have not deleted before
$post = Post::find($id);

// If you have soft-deleted it before
$post = Post::withTrashed()->find($id);

$post->forceDelete(); // This permanently deletes the post for ever!

// Additional logic...
}

Keep an eye on your database’s performance when dealing with soft deletes. Large tables with many soft-deleted records can affect query performance.

Wow! What if I want to get the list of both deleted and non-deleted records?

Very simple. Just use the withTrashed() that comes with SoftDelete trait. Allow me to show you:

$posts = Post::withTrashed()->get();

This query will give you all posts, both trashed and non-trashed.

Before you ask, you can also get only deleted records, yes. There’s another nice method: onlyTrashed() . See it in action;

$trashedPosts = Post::onlyTrashed()->get();

This query will return only the soft-deleted posts.

My advice? Use Sparingly.

Soft deletes in Laravel are a powerful tool for managing data responsibly. However, to make the most of this feature, you should follow best practices and be aware of potential pitfalls.

Implement Soft Deletes Sparingly: Not all tables require soft deletes. Reserve this feature for tables where data recovery or compliance with data retention policies is essential.

Understand the Difference: Clearly understand the difference between soft deletes and permanent deletes. Use delete() for soft deletes and forceDelete() for permanent ones.

Customize Timestamps: — Laravel uses the deleted_at column by default for soft deletes. You can customize this column name if needed using the $deletedAt property in your model.

Conclusion

Soft deletes in Laravel provide a safety net for data management, offering the flexibility to mark data as deleted while retaining the ability to recover it when necessary. By implementing soft deletes and adhering to best practices, you can enhance data management, maintain compliance, and optimize database performance in your Laravel applications. Your next step? Start integrating soft deletes into your Laravel projects and experience the benefits firsthand.

Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some clap 👏. And if you have any questions feel free to comment.

Thank you.

Thanks a lot for reading till end. Follow or contact me via:
Twitter: https://twitter.com/EjimaduPrevail
Email: prevailexcellent@gmail.com
Github: https://github.com/PrevailExcel
LinkedIn: https://www.linkedin.com/in/chimeremeze-prevail-ejimadu-3a3535219
BuyMeCoffee: https://www.buymeacoffee.com/prevail
Chimeremeze Prevail Ejimadu

--

--

Chimeremze Prevail Ejimadu

Laravel Developer + Writer + Entrepreneur + Open source contributor + Founder + Open for projects & collaborations. Hit FOLLOW ⤵