Azis Hapidin
Working with Soft Delete in Laravel

Laravel Soft Delete is a feature that allows you to restore deleted data on the app, it will very helpful in case sometime your user accidentally deletes data on the app. Soft Delete is included by default on Laravel Framework.

It works by adding the created_at field on the table that you want to use Soft Delete, the default value of this field is null, null value means the data is active (not deleted), and filled mean data is marked delete and will not show by default on your app. When users delete data on the app, the created_at field will be filled by the current timestamp, and when you restore data it will be filled by null value again.

In this article, we will implement Soft Delete on the User model, before you continue I assumed you have a Laravel project with a database that has been set up.

Add Soft Delete (deleted_at) field on Database Table

The first thing you must do is add the Soft Delete field on the users table, if you have not yet migrated your database you can easily add the line below on users migration.

$table->softDeletes();

But if you have been migrated your database and there some data on users table, you must create a new migration. Because if you roll back the migration the data on users table will be deleted. You can create new migration by running this command on the terminal:

php artisan make:migration add_soft_delete_on_users_table

It will create xx_xx_xx_xxxxxx_add_soft_delete_on_users_table.php, fill like this:

<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class AddSoftDeleteOnUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->softDeletes();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table("users", function ($table) {
            $table->dropSoftDeletes();
        });
    }
}

Then, just run artisan migrate to execute it to your database:

php artisan migrate

Add Soft Delete Trait on User Model

Next, we must add Soft Delete Trait Illuminate\Database\Eloquent\SoftDeletes on User model:


<?php
 
namespace App;
 
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes; // <<== Add this line
 
class User extends Authenticatable
{
    use SoftDeletes; // <<== And this
    use Notifiable;
 
    ....
}

If nothing wrong the Soft Delete feature can be used on the User right now, so let’s test it.

Testing

Because this article just explains Soft Delete and not about CRUD I will explain how to use this feature on Laravel Tinker 😬

First, we create 2 dummy users for testing via Tinker:

Then make sure that data is successfully saved in the database:

Ok now we try to delete the first user that we’ve been inserted before:

While we retrieve again the users data, it will only show 1 data:

Now we check it on the database, the user that has been deleted is still there but with delete_at filled:

So from now while we retrieve users data, it will only include the users that deleted_at is null:

Retrieve Deleted Data

Now the question is how to get deleted data? In this case, we can use withTrashed() and onlyTrashed() method. withTrashed() will query all data including deleted and active data, and onlyTrashed() will query ONLY deleted data.

// Query all data (deleted and not deleted)

$users = User::withTrashed()->where('email', '[email protected]')->get();

// Query only deleted data

$users = User::onlyTrashed()->where('email', '[email protected]')->get();

Permanently Delete the Data

If we want to permanently delete the data from the database, we can use forceDelete() method:

$user = User::withTrashed()->where('email', '[email protected]')->first()

// Permanently delete from database

$user->forceDelete();

Restore the Data

In real case sometimes we need to restore deleted data, we can use restore() method.

$user = User::withTrashed()->where('email', '[email protected]')->first()

// Restore data

$user->restore();

Conclusion

It is easy to use Soft Delete In Laravel, we just need to add a field on the database and add traits in the model, and boom Soft Delete is ready to use on our project.