How to use soft delete in laravel eloquent

How to use soft delete in laravel eloquent

Before we see How to use soft delete in laravel, let first see what is soft delete

Soft delete is a way to mark a record as deleted so we can ignore such a record when we retrieve records from that table. Laravel provides SoftDeletes trait that we can use with any Laravel eloquent model.

Benefit of soft delete is that it does not actually remove the record from the table the same way the delete operation does. So we can recover the soft deleted record if we require it in future.

Adding Soft delete feature to our model

1. Add deleted_at column in our database table

We can do this manually using any database administration tool or using laravel migration. Let’s first create a migration and update according to our requirements.

Let’s create migration using below artisan command:

php artisan make:migration add_column_deleted_at  –table=trees 

Structure of migration will be as given below:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
Schema::table('trees', function (Blueprint $table) {
   $table->softDeletes();
});
 
Schema::table('trees', function (Blueprint $table) {
   $table->dropSoftDeletes();
});

2. Use SoftDeletes trait in our modal

Laravel provides SoftDeletes trait and so adding a soft delete function to any model is very simple, just use SoftDeletes trait in the model and that’s it.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
 
class Tree extends Model
{
   use SoftDeletes;
}

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp and will be marked as deleted.

Restoring Soft Deleted Models

Sometimes, we need to “un-delete” a soft deleted model. To restore a soft deleted model, you can call the restore method on a model instance. The restore method will set the model’s deleted_at column to null.

$tree->restore();

You may also use the restore method in a query to restore multiple models.

Tree::withTrashed()
       ->where('name', 'Oak')
       ->restore();

Permanently Deleting Models

Sometimes, you need to permanently remove the model from your database. So for that, you can use forceDelete method to permanently remove a soft deleted model from your database table:

$tree->forceDelete();

Retrieving Soft Deleted Models

So, soft deleted models will be automatically excluded from query results, if you want to still retrieve soft deleted models, use withTrashed as shown below:

use App\Models\Tree;
 
$trees = Tree::withTrashed()
               ->where('name', 'Oak')
               ->get();

Retrieving Only Soft Deleted Models

The onlyTrashed method will retrieve only soft deleted models:

$trees = Tree::onlyTrashed()
               ->where('name', 'Oak')
               ->get();

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments