PHP
Implement and Manage Soft Deletes in Eloquent Models
Learn how to enable and utilize soft deletes in Laravel Eloquent, allowing you to logically delete records without permanently removing them from the database, and how to restore them.
// 1. Add 'deleted_at' column to your table migration
// public function up() {
// Schema::create('posts', function (Blueprint $table) {
// $table->id();
// $table->string('title');
// $table->text('body');
// $table->timestamps();
// $table->softDeletes(); // Adds deleted_at timestamp column
// });
// }
// 2. In your Post model (App/Models/Post.php)
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Important
class Post extends Model
{
use HasFactory, SoftDeletes; // Add the trait
// ...
}
// Usage:
$post = App\Models\Post::find(1);
// Soft delete a post
$post->delete(); // Sets 'deleted_at' timestamp
echo "Post " . $post->id . " soft-deleted.
";
// Attempt to find the soft-deleted post (will return null by default)
$deletedPost = App\Models\Post::find(1); // null
echo "Attempted to find post (normal query): " . (isset($deletedPost) ? "Found" : "Not Found") . "
";
// Retrieve soft-deleted posts
$allPostsIncludingDeleted = App\Models\Post::withTrashed()->get();
echo "Total posts (including soft-deleted): " . $allPostsIncludingDeleted->count() . "
";
$onlyDeletedPosts = App\Models\Post::onlyTrashed()->get();
echo "Only soft-deleted posts: " . $onlyDeletedPosts->count() . "
";
// Restore a soft-deleted post
$post->restore(); // Sets 'deleted_at' to null
echo "Post " . $post->id . " restored.
";
// Force delete (permanently remove)
// $post->forceDelete();
How it works: This snippet explains how to implement soft deletes in Laravel Eloquent. By adding the `SoftDeletes` trait to an Eloquent model and a `deleted_at` column to its database table, records are not permanently removed when `delete()` is called; instead, their `deleted_at` timestamp is set. This allows for logical deletion and easy restoration using the `restore()` method. The `withTrashed()` and `onlyTrashed()` methods provide ways to query for models that are soft-deleted or both active and soft-deleted, respectively, offering flexibility in data management without actual data loss.