PHP

Implementing Soft Deletion for Eloquent Models

Learn to implement soft deletion in Laravel Eloquent models, allowing records to be 'deleted' without permanent removal from the database, improving data integrity.

<?php

namespace App\Models;

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

class Post extends Model
{
    use SoftDeletes;

    // ... other model properties and methods

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
}

// Usage:
$post = App\Models\Post::find(1);
if ($post) {
    $post->delete(); // Soft deletes the post (sets 'deleted_at' timestamp)
    echo "Post #1 soft deleted.
";
}

// Retrieve only non-deleted posts (default behavior)
$activePosts = App\Models\Post::all();
echo "Active posts count: " . $activePosts->count() . "
";

// Retrieve all posts, including soft deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
echo "All posts (including trashed) count: " . $allPosts->count() . "
";

// Retrieve only soft deleted posts
$trashedPosts = App\Models\Post::onlyTrashed()->get();
echo "Trashed posts count: " . $trashedPosts->count() . "
";

// Restore a soft deleted post
$trashedPost = App\Models\Post::onlyTrashed()->find(1);
if ($trashedPost) {
    $trashedPost->restore();
    echo "Post #1 restored.
";
}

// Permanently delete a soft deleted post
$trashedPost = App\Models\Post::onlyTrashed()->find(2);
if ($trashedPost) {
    $trashedPost->forceDelete();
    echo "Post #2 permanently deleted.
";
}
How it works: Soft deletion allows you to "delete" records without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. This is highly useful for auditing, data recovery, or maintaining historical data. To enable it, simply use the `SoftDeletes` trait in your Eloquent model and add a `deleted_at` column to your database table (e.g., via a migration). Eloquent queries will automatically exclude soft-deleted records unless `withTrashed()` or `onlyTrashed()` is explicitly used. You can restore records with `restore()` or permanently remove them with `forceDelete()`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs