Hello Laravel Developers,

Today we will learn about Soft Delete in Laravel 8.

Data is crucial for any Laravel project. Sometimes we accidentally delete some data, which means it is gone permanently and we cannot restore it. This will create issues if the data is used in other project parts. To avoid issues, there comes the need for Soft Delete.

Let’s understand what soft delete is and why it is used

What is Soft Delete in Laravel?

The soft delete feature in Laravel never deletes data from the database. It just prevents the data from showing. The soft delete data can be restored back or permanently deleted from the database.Β Β 

Why do we need to Use Soft Delete in Laravel?

As mentioned, soft delete does not actually remove data from the database. A deleted attribute is set on the model that indicates the date and time when it was deleted. For the purpose of data safety and backup, we use the soft delete in Laravel.

Let’s see how to use soft delete in Laravel.

Steps to Implement Soft Delete in Laravel 8:

Step 1: Create MigrationΒ 

Now you can find the deleted_at column in your companies table.

Step 2: Create a Model

To enable soft deletes for a model, add theΒ 

Illuminate\Database\Eloquent\SoftDeletes trait to the model:

The SoftDeletes trait will automatically cast the deleted_at attribute to a DateTime / Carbon instance for you.

Step 3: Get Records

You can get all records like as below,Β 

It will return all records that have deleted_at = null only

You can also get deleted records with soft delete.

Conclusion:

Hence, it was all about using Soft Delete in Laravel 8. Avoid permanent loss of your critical data by implementing the Laravel soft delete feature. Share the article with your friends and stay in touch with us.Β 

Happy Coding!

Click to rate this post!
[Total: 18 Average: 4.2]