PHP
Implementing Soft Deletes for Records in Laravel Eloquent
Use Laravel's soft deletes to mark records as 'deleted' without actually removing them from the database, allowing for easy restoration.
// In App\Models\Post.php
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
// Usage:
$post = App\Models\Post::find(1);
$post->delete(); // Marks 'deleted_at' timestamp
// Retrieve only non-deleted posts
$activePosts = App\Models\Post::all();
// Retrieve all posts, including soft deleted
$allPosts = App\Models\Post::withTrashed()->get();
// Retrieve only soft deleted posts
$deletedPosts = App\Models\Post::onlyTrashed()->get();
// Restore a soft deleted post
$deletedPost = App\Models\Post::withTrashed()->find(1);
$deletedPost->restore();
// Permanently delete a post
$post->forceDelete();
How it works: Soft Deletes provide a convenient way to 'archive' records instead of permanently removing them from your database. By adding the 'SoftDeletes' trait to your model and a 'deleted_at' timestamp column to your table, Eloquent will automatically set this timestamp instead of truly deleting the row when 'delete()' is called. This feature allows for easy restoration of records and maintaining data integrity, acting as a 'trash can' for your models.