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.
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();
});
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;
...
...
...
}
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.
if ($article->trashed()) {
//
}
$articles = Article::withTrashed()->all();
$articles = Article::onlyTrashed()->all();
$article->delete();
// or
$article->deleted_at = Carbon::now();
$article->save();
$article->restore();
// or
$article->deleted_at = null;
$article->save();
$article->forceDelete();