PHP
Implementing Eloquent Soft Deletes
Learn how to implement soft deletes in Laravel Eloquent models, allowing you to "delete" records without permanently removing them from your database.
// In your migration file
Schema::table('posts', function (Blueprint $table) {
$table->softDeletes();
});
// In your Post model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
// ... other model properties and methods
}
// Usage examples
// Delete a post (soft deletes it)
$post = App\Models\Post::find(1);
$post->delete();
// Retrieve all posts, including soft-deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
// Retrieve only soft-deleted posts
$deletedPosts = App\Models\Post::onlyTrashed()->get();
// Restore a soft-deleted post
$post = App\Models\Post::withTrashed()->find(1);
$post->restore();
// Permanently delete a post
$post = App\Models\Post::withTrashed()->find(1);
$post->forceDelete();
How it works: Soft deletes in Eloquent allow you to mark records as "deleted" by setting a `deleted_at` timestamp instead of truly removing them from the database. To use soft deletes, add the `softDeletes()` column to your migration and use the `SoftDeletes` trait in your model. Eloquent queries will then automatically exclude soft-deleted records, but you can retrieve, restore, or force-delete them using dedicated methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()`.