Laravel Eloquent Soft Delete

Eloquent Models Laravel Eloquent Soft Delete

In this article, we'll delve into Laravel's Eloquent ORM and explore its powerful "soft delete" feature. We'll discuss how to implement soft deletes for your models, understand its benefits, and learn how to work with soft-deleted records effectively.

Migration

To enable soft deletes, add a deleted_at column to your table. The Laravel schema builder provides a convenient method for this.

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

Model

The SoftDeletes trait handles automatic casting of the deleted_at attribute to a DateTime or Carbon object.

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

Working with SoftDeletes

Soft deletes mark a model as deleted by setting the deleted_at column to the current timestamp instead of physically removing the record from the database. This allows you to easily restore soft-deleted models if necessary. When querying, soft-deleted models are automatically excluded from the results unless explicitly included.

Check Trashed Models

if ($article->trashed()) {
    // 
}

Get Also Trashed Models

$articles = Article::withTrashed()->all();

Retrieving Only Trashed Models

$articles = Article::onlyTrashed()->all();

Soft Delete Model

$article->delete();
// or
$article->deleted_at = Carbon::now();
$article->save();

Restore Soft Deleted Model

$article->restore();
// or
$article->deleted_at = null;
$article->save();

Delete Model Permanently

$article->forceDelete();