PHP

Implementing and Querying Soft Deletes in Eloquent

Learn how to implement soft deletes in Laravel Eloquent models, allowing you to 'delete' records without permanently removing them from the database and how to query them.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'content'];

    // Example usage:
    // $post = Post::find(1);
    // $post->delete(); // Soft deletes the post

    // Post::withTrashed()->find(1); // Retrieve a soft-deleted post
    // Post::onlyTrashed()->get();   // Retrieve only soft-deleted posts

    // Post::withTrashed()->find(1)->restore(); // Restore a soft-deleted post
    // Post::onlyTrashed()->find(1)->forceDelete(); // Permanently delete a soft-deleted post
}
How it works: This snippet demonstrates how to enable and use Laravel's soft deletes feature. By using the `SoftDeletes` trait on an Eloquent model and adding a `deleted_at` timestamp column to your database table, records are not permanently removed upon deletion. Instead, the `deleted_at` column is set. Eloquent queries will automatically exclude soft-deleted records. You can use `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` methods to interact with soft-deleted models.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs