How to perform Soft Delete in Laravel [Tutorial]


Written By - Muhammad Azeem
Advertisement

Definition of Laravel Soft Delete

Laravel soft delete is a feature that allows developers to delete data from the database without actually deleting it. Instead, the data is marked as “deleted” in the database and is no longer accessible from the application. This provides a better way to manage data in applications as it allows developers to store deleted data and provides an easy way to recover it if needed.

Let’s take an example of a blog with posts. If a user decides to delete a post, the usual approach would be to delete the post from the database. However, this could lead to data loss if the user later decides to recover the post. With Laravel soft delete, the deleted post is still stored in the database but it is marked as deleted and not accessible from the application. This provides a better way to handle the data as it can be easily recovered if needed.

To use Laravel soft delete, the developer needs to include the “SoftDeletes” trait in the model. This will add a “deleted_at” column to the model which is used to store the timestamp of when the record was deleted. This allows the developer to query the database and retrieve records that have been soft deleted.

For example, if we are using the blog example, we would use the following query to retrieve all posts that have been soft deleted:

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

This will retrieve all posts that have been marked as deleted and are not accessible from the application.

In conclusion, Laravel soft delete is a great way to manage data in applications. It allows developers to keep deleted data and provides an easy way to retrieve it if needed.

 

Benefits of Using Soft Delete

Soft delete is a feature that allows users to delete data from a database without actually removing it from the database. This feature is becoming increasingly popular as businesses and organizations strive to ensure the security and integrity of their data.

Benefits of Soft Delete

Advertisement
  1. Data Recovery: Soft delete allows users to recover deleted data if they accidentally delete something. This makes it much easier to restore data that was mistakenly removed.
  2. Data Security: By using soft delete, businesses and organizations can ensure the security and integrity of their data. This feature helps protect data from malicious users who may try to delete important information.
  3. Improved Performance: Soft delete helps improve database performance as there is less need to store deleted data. This can help save storage space and improve performance.
  4. Easier Auditing: Soft delete also makes it easier to audit data as deleted data is still available in the database. This makes it easier to track any changes or deletions that have been made.

Example of Soft Delete

Let's say you have a database that contains employee records. You can use soft delete to allow users to delete records from the database without actually removing them from the database. This way, users can still access the deleted records if they need to recover them or for auditing purposes.

In conclusion, soft delete is a great feature for businesses and organizations that need to ensure the security and integrity of their data. It helps improve performance and makes it easier to audit data.

 

Implementation of Laravel Soft Delete

Create a Migration

Migrations are used in Laravel to keep track of changes in the database structure, such as creating tables, adding columns, or dropping columns. They are written in PHP and stored in the database/migrations directory. A migration is a single file that contains all of the necessary SQL commands to create or modify a database.

Let’s take an example of creating a migration to create a users table.

First, we need to create a new migration file:

php artisan make: migration create_users_table

This will create a new file in the database/migrations directory with a timestamp as part of the filename.

The new migration file will contain two methods: up() and down(). The up() method is used to add new tables, columns, or indexes to the database. The down() method is used to remove them.

Advertisement

In our example, we’ll add the following code to the up() method:

Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });

This code will create a users table with an auto-incrementing id field, a name field, an email field that must be unique, a password field, a rememberToken field, and two timestamps fields for created_at and updated_at.

Now we can run the migration to create the table:

php artisan migrate

This will create the users table in the database.

 

Enable Soft Deletes

In this article, we will explore how to enable soft deletes in Laravel, and provide an example of how to use them.

First, let’s take a look at how to enable soft deletes in Laravel. To do this, you need to add the SoftDeletes trait to your model. This will enable the deleted_at column on the model.

Advertisement

For example, if you have a User model, you can enable soft deletes like this:

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

Once you have added the SoftDeletes trait to the model, you can use the delete() method to soft delete a record. This method sets the deleted_at timestamp on the record. You can also use the restore() method to undo a soft delete, and the forceDelete() method to hard delete a record.

Now let’s look at an example of how to use soft deletes. We’ll use the same User model from before.

First, let’s create a new user:

$user = new User;
$user->name = ‘John Doe’;
$user->save();

Now, let’s soft delete the record:

$user->delete();

At this point, the record will still exist in the database, but the deleted_at timestamp will be set.

Finally, let’s restore the record:

$user->restore();

Now, the record will be returned in queries, and the deleted_at timestamp will be null.

In this article, we explored how to enable soft deletes in Laravel, and provided an example of how to use them. Soft deletes are a useful feature when you want to retain deleted records in the database, but prevent them from being returned in queries.

 

Use Soft Deletes in Model

To use Soft Deletes in Laravel, you must first make sure your model extends the SoftDeletes trait. This gives you access to some useful methods such as the deleted-at column and the “forceDelete()” method.

Advertisement

Let’s say you have a model called User. To use Soft Deletes, you need to make sure your model looks like this:

<?php

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
  use SoftDeletes;

  protected $dates = ['deleted_at'];
}

The SoftDeletes trait provides a deleted_at column that you can use to store the timestamp of when the row was deleted. You can also use the “forceDelete()” method to permanently delete a row from the database.

To delete a row from the database using Soft Deletes, you need to call the delete() method on the model. This will set the deleted_at timestamp, but will not actually delete the row from the database.

$user = User::find(1);
$user->delete();

If you need to retrieve the deleted rows, you can use the “withTrashed()” method. This will return all the rows, even the ones marked as deleted.

$users = User::withTrashed()->get();

And if you need to permanently delete a row from the database, you can use the “forceDelete()” method.

$user = User::find(1);
$user->forceDelete();

Soft Deletes are an incredibly powerful tool for managing data in Laravel. It allows you to easily mark data as deleted without actually deleting it from the database, which can be useful for data integrity.

 

Recommendation to Use Soft Delete

To use soft delete in Laravel, you will first need to enable the feature. This can be done by setting the ‘softdeletes’ option in the model. To do this, open the model file and add the following line:

protected $softDelete = true;

Once the option is set, the model will be able to detect if the record is marked as deleted and will not be included in the query results. This is how Laravel handles soft deletes.

To demonstrate how to use soft delete in Laravel with an example, let’s assume that we have a model called ‘User’ with a ‘deleted_at’ column. To soft delete a user, we can use the following code:

User::find(1)->delete();

This will set the ‘deleted_at’ column to the current timestamp, which is how Laravel detects that the record has been soft deleted.

Advertisement

To restore a soft deleted record, we can use the following code:

User::withTrashed()->find(1)->restore();

This will set the ‘deleted_at’ column to null, which is how Laravel detects that the record has been restored.

Now that we have discussed how to use soft delete in Laravel with an example, let’s look at some best practices for implementing soft delete in Laravel.

First, it is important to note that soft delete should only be used when necessary. If your application does not need to track changes over time, it may be better to permanently delete records instead.

First, it is important to note that soft delete should only be used when necessary. If your application does not need to track changes over time, it may be better to permanently delete records instead.

Finally, when implementing soft delete in Laravel, it is important to consider the performance implications. Soft delete queries can be slower than regular delete queries, so it is important to consider the performance impact before implementing this approach.

In conclusion, soft delete in Laravel is a powerful feature that allows data to be easily restored in the event of an accidental deletion. This approach can also be used to create history logs for data, allowing for easy auditing of changes. When using soft delete in Laravel, it is important to ensure that the records are not accessible to users and consider the performance implications.

 

Further Reading

Laravel Soft Delete posts - Stack Overflow
Laravel Soft Deleting

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment