PHP
Implementing Soft Deletes in Laravel Eloquent
Learn how to implement soft deletes in your Laravel Eloquent models, allowing you to 'archive' records instead of permanently deleting them, with easy restoration.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
// ... other model properties and methods
// In a migration:
// Schema::table('posts', function (Blueprint $table) {
// $table->softDeletes();
// });
}
// Usage:
// $post = Post::find(1);
// $post->delete(); // Sets `deleted_at` timestamp, doesn't remove from DB
// Retrieve only non-deleted posts:
// $activePosts = Post::all();
// Retrieve all posts, including soft deleted:
// $allPosts = Post::withTrashed()->get();
// Retrieve only soft deleted posts:
// $trashedPosts = Post::onlyTrashed()->get();
// Restore a soft deleted post:
// $trashedPost = Post::withTrashed()->find(1);
// $trashedPost->restore();
// Force delete a post (permanently):
// $post->forceDelete();
How it works: Soft Deletes allow you to logically delete records without removing them from your database. By using the `SoftDeletes` trait on your Eloquent model and adding a `deleted_at` timestamp column to your table, Eloquent will automatically set this timestamp instead of truly deleting the record. You can then easily retrieve, restore, or force-delete these records using dedicated methods like `withTrashed()`, `onlyTrashed()`, and `restore()`.