Soft Delete in Laravel

In Laravel, “soft delete” refers to the practice of marking records as deleted instead of physically removing them from the database. Soft deleting is often used when you want to retain a record of the data but indicate that it should be considered as “deleted” in the application. This is achieved by adding a deleted_at column to the database table, and when a record is soft deleted, this column is set with a timestamp, marking the record as “deleted.”

Here’s a simple example of using soft deletes in Laravel:

1. Database Migration:

First, you need to add a deleted_at column to your database table. If you’re using Eloquent, Laravel’s ORM, this can be achieved with the softDeletes method in your migration file:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->softDeletes(); // Adds 'deleted_at' column
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

2. Eloquent Model:

Next, in your Eloquent model (e.g., Post), use the SoftDeletes trait:

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

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'content'];
    protected $dates = ['deleted_at'];
}

The SoftDeletes trait provides the necessary methods to work with soft deletes.

3. Soft Deleting Records:

Now you can use soft deletes when deleting records. When a record is soft deleted, the deleted_at column is set with the current timestamp.

// Soft delete a post
$post = Post::find(1);
$post->delete();

// Check if a record is soft deleted
if ($post->trashed()) {
    // The post has been soft deleted
}

// Retrieve all posts (including soft deleted ones)
$allPosts = Post::withTrashed()->get();

// Retrieve only soft deleted posts
$softDeletedPosts = Post::onlyTrashed()->get();

4. Restoring and Force Deleting:

You can restore soft-deleted records using the restore method and force delete them permanently using the forceDelete method:

// Restore a soft-deleted post
$post->restore();

// Permanently delete a soft-deleted post
$post->forceDelete();

Soft deletes provide a way to keep a historical record of deleted data while allowing for easy restoration if needed. This is particularly useful in scenarios where accidental deletions or the need for audit trails arise.

Leave a comment

Your email address will not be published. Required fields are marked *