PHP

Implementing Soft Deletes in Eloquent Models

Learn how to implement soft deletes in Laravel Eloquent to gracefully manage deleted records, allowing for easy restoration instead of permanent removal.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    // Optionally, define the 'deleted_at' column in $casts for explicit type hinting
    protected $casts = [
        'deleted_at' => 'datetime',
    ];

    // ... other model properties and methods
}

// --- Usage Examples ---

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

// Retrieve only non-deleted posts
$activePosts = Post::all();

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

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

// Restore a soft-deleted post
$post = Post::withTrashed()->find(1);
if ($post && $post->trashed()) {
    $post->restore();
}

// Permanently delete a post (force delete)
$post = Post::withTrashed()->find(1);
if ($post) {
    $post->forceDelete();
}
How it works: This snippet demonstrates how to use Laravel's `SoftDeletes` trait to avoid permanent deletion of records. By adding `use SoftDeletes;` to your model and ensuring a `deleted_at` timestamp column exists in your database table, records will be marked as deleted instead of being removed entirely. Eloquent provides methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to interact with soft-deleted records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs