PHP

Implement Soft Deletes for Logical Data Deletion in Eloquent

Learn how to use Laravel Eloquent's soft deletes to logically remove records without permanent deletion, enabling restoration and permanent removal when needed.

// In app/Models/Comment.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Don't forget to import this!

class Comment extends Model
{
    use SoftDeletes; // Add the trait to your model

    protected $dates = ['deleted_at']; // Optional: specify the column if not default 'deleted_at'
}

// In a controller or service
use App\Models\Comment;

// Create a new comment
$comment = Comment::create(['content' => 'This is a test comment.', 'user_id' => 1]);
echo "Comment created with ID: " . $comment->id . "
";

// "Delete" the comment (soft delete)
$comment->delete();
echo "Comment ID " . $comment->id . " soft deleted.
";
// Now, Comment::all() will NOT include this comment by default.
// Comment::find($comment->id) will return null.

// Retrieve ALL comments, including soft deleted ones
$allComments = Comment::withTrashed()->get();
echo "Total comments (including soft deleted): " . $allComments->count() . "
";

// Retrieve ONLY soft deleted comments
$trashedComments = Comment::onlyTrashed()->get();
echo "Only trashed comments: " . $trashedComments->count() . "
";

// Restore a soft deleted comment
Comment::withTrashed()->find($comment->id)->restore();
echo "Comment ID " . $comment->id . " restored.
";
// Now, Comment::all() will include this comment again.

// Permanently delete a comment (force delete)
$commentToDelete = Comment::create(['content' => 'Another comment to be force deleted.', 'user_id' => 1]);
echo "Comment created for force deletion with ID: " . $commentToDelete->id . "
";
$commentToDelete->forceDelete();
echo "Comment ID " . $commentToDelete->id . " force deleted permanently.
";
// This comment is now gone from the database.
How it works: Soft deleting allows you to mark records as "deleted" by setting a `deleted_at` timestamp rather than physically removing them from the database. This is useful for auditing, data recovery, and maintaining historical data. By using the `SoftDeletes` trait, Eloquent automatically handles filtering out soft-deleted records from standard queries. You can then use methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to manage these logically 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