← Back to all snippets
PHP

Implementing Soft Deletes for Data Recovery in Eloquent

Enable soft deleting in Laravel Eloquent to gracefully mark records as deleted instead of permanently removing them, allowing for easy data recovery.

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

class Product extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    // protected $dates = ['deleted_at']; // Not explicitly needed in Laravel 8+ due to Carbon
}

// Usage Example:
$product = Product::find(1);
$product->delete(); // Soft deletes the product, sets 'deleted_at' timestamp

$activeProducts = Product::all(); // Will not include soft deleted products
$allProducts = Product::withTrashed()->get(); // Includes soft deleted products
$onlyDeleted = Product::onlyTrashed()->get(); // Only retrieves soft deleted products

$product->restore(); // Restores the soft deleted product by setting 'deleted_at' to null
$product->forceDelete(); // Permanently deletes the product from the database
How it works: Soft Deleting allows you to 'delete' records without actually removing them from your database, providing a safety net for data recovery. By simply adding the `SoftDeletes` trait to your model, calling the `delete()` method will set a `deleted_at` timestamp on the record instead of permanent removal. Eloquent then automatically excludes these 'deleted' records from future queries. You can easily retrieve, restore, or permanently delete these records using methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs