Hello 👋

This is Hamid Afghan a software developer, Building web and mobile applications with Laravel, JavaScript and Node JS. Here, I try to share everything about the technologies I work with and the life experiences. Check the list of articles or the recent posts below.

Blog

Tutorial

Life

Laravel Eloquent Soft Delete in Large Tables

Apr 12, 2022

Laravel Eloquent provides a soft delete feature that enables to delete records temporarily and be able to restore them. This feature was released in version 6.

Eloquent model flags the records with the `deleted_at` database column as deleted records. Laravel provides various methods to restore, query deleted records, and finally restore them safely.

To dive deep, into retrieval data Laravel model scan the full table which might be a very big performance risk for the table having large data.

# app\Models\User.php
<?php

namespace App;

class User extends Authenticatable{
    use SoftDeletes;
// ...
}

# user migration
Schema::table('users', function (Blueprint $table) {
  $table->softDeletes();
});

Adding SoftDeletes traits and `$table->softDeletes();` add the functionlity of soft detele to user model.

But, while running the below query, Laravel Model will do a full table scan which reduces the query performance in large tables.

App\Models\User::all()

// SQL command

SELECT * FROM USERS WHERE deleted_at IS NULL;

So while implementing Laravel soft delete need to think twice and decide if it is a good idea to add a full table scan?!

Thanks

The Best