What is soft delete in Laravel?

Photo by Growtika on Unsplash

What is soft delete in Laravel?

In Laravel, soft delete is a feature that allows you to "delete" a record from a database table without actually removing it physically. Instead of permanently deleting the record, a timestamp is set on a special "deleted_at" column, indicating when the record was soft deleted. This allows you to retain information about the deleted records and, if necessary, recover them later.

To implement soft deletes in Laravel, you typically follow these steps:

  1. Database Migration: Add a "deleted_at" column to your table. You can use the softDeletes method in your migration file:
Schema::table('your_table', function ($table) {
    $table->softDeletes();
});
  1. Model Configuration: In your Eloquent model, use the SoftDeletes trait, which is included with Laravel:

     use Illuminate\Database\Eloquent\Model;
     use Illuminate\Database\Eloquent\SoftDeletes;
     class YourModel extends Model
     {
         use SoftDeletes;
     }
    
  2. Usage: Now, when you delete a record using Eloquent, it will be a soft delete, and the "deleted_at" column will be set to the current timestamp:

     YourModel::find($id)->delete();
    

    To retrieve soft-deleted records, you can use the withTrashed method:

     $softDeletedRecords = YourModel::withTrashed()->get();
    

    To only retrieve soft-deleted records, you can use the onlyTrashed method:

     $softDeletedRecords = YourModel::onlyTrashed()->get();
    

    To restore a soft-deleted record, you can use the restore method:

     YourModel::withTrashed()->find($id)->restore();
    

    To permanently remove soft-deleted records, you can use the forceDelete method:

     YourModel::withTrashed()->find($id)->forceDelete();
    

    Soft deletes are useful in scenarios where you want to keep a record of deleted items for audit purposes or in case you need to recover deleted data.