PHP

Implementing Soft Deletion for Laravel Eloquent Models

Learn how to implement soft deletion in Laravel Eloquent models, allowing you to "delete" records without permanently removing them from your database, enabling easy restoration.

// In App\Models\Post.php
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    // ... other model properties and methods
}

// In your migration for 'posts' table
Schema::table('posts', function (Blueprint $table) {
    $table->softDeletes(); // Adds 'deleted_at' timestamp column
});

// Usage
$post = App\Models\Post::find(1);
$post->delete(); // Sets 'deleted_at' timestamp

// Retrieve only non-deleted posts (default behavior)
$activePosts = App\Models\Post::all();

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

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

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

// Permanently delete a soft-deleted post
$post->forceDelete();
How it works: Soft deletion in Laravel Eloquent allows you to mark records as "deleted" by setting a `deleted_at` timestamp, rather than physically removing them from the database. This is achieved by using the `SoftDeletes` trait in your model and adding a `deleted_at` column to your table. This feature is invaluable for auditing, compliance, or simply providing an "undo" option for deletions. Eloquent automatically excludes soft-deleted records from standard queries unless `onlyTrashed()` or `withTrashed()` methods are explicitly used.

Need help integrating this into your project?

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

Hire DigitalCodeLabs