How to Use Soft Delete in Laravel 5

In addition to deleting the records, Laravel’s Eloquent also allows you to perform Soft Delete. In Soft Delete,  a deleted_at column is added to your database table. By default, all records contains NULL value in deleted_at column. When a record has NON-NULL deleted_at value it is considered soft deleted. Soft deleted records are excluded from Eloquent’s query results by Laravel.

In this tutorial, we are going to implement Soft Delete feature.

Step 01 : Add deleted_at Column to Database

Before using soft delete feature you need to add a deleted_at column to database table. Laravel’s Schema builder comes with a built-in method to create this column.

Schema::table('motorcycles', function ($table) {
    $table->softDeletes();
});

Step 02 : Use the Soft Delete Trait in the Model.

<?php

namespace App;

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

class Motorcycle extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
	
	/**
     * The table used by the model.
     *
     * @var string
     */
    protected $table = 'motorcycles';
}

To enable Soft Deletes, use Illuminate\Database\Eloquent\SoftDeletes trait inside your model and add deleted_at to $dates property.

Now, you can soft delete a record using the delete method.

public function destroy($id)
{
	$motorcycle = Motorcycle::find(8);
	$motorcycle->delete();
}

The above code will set the deleted_at value for that specific record to current date and time i.e. non-null value.

Laravel Tip : Rendering View to a String

2 Comments

  1. Thanks for this,very insightful. I observed something i consider weird though, when a model is deleted, i checked my database expecting to see an entry in the deleted_at field and the row still in the database but the row is deleted. Where did it go? i dont quite understand what’s going on here, kindly explain

    Reply
    • I think you have not configured your model properly. Make sure you have referenced Soft Deletes trait inside your model.
      use Illuminate\Database\Eloquent\SoftDeletes;

      On more thing.
      This will only work with Eloquent. Soft Deletes does NOT support query builder.

      Reply

Leave a Comment.