Soft Delete Records With Laravel

By Michael Williams, Published on 06/09/2018

When working with data such as users or user related records. Sometimes you may want to soft delete the data rather than permanently removing it. One advantage to soft deletes is easy restore in the event of an accidental delete by someone, but the use cases are unlimited. Luckily, in Laravel the setup for this is quite simple.

First, your table will need to have a deleted_at column, which can be easily added at creation time or through a future migration.

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

Your model will also need to use SoftDeletes.

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }

Now when you call delete() on your model. The deleted_at column will get updated. The beauty here is when using Eloquent. Deleted data will automatically be omitted from results, so no further action is needed.

You can restore a record in the future by running restore() on your model. Alternately, if you wanted to permanently remove the record(s) you may do so by running forceDelete().