Skip to content

Soft Deletes Auditable

For applications that need to track who deleted records, use AuditableWithDeletesTrait instead of AuditableTrait.

::: tip Feature Comparison This trait extends the basic AuditableTrait functionality. See the Feature Comparison table for a complete comparison. :::

Requirements

  1. Add the deleted_by column to your table
  2. Use AuditableWithDeletesTrait on your model
  3. Use Laravel's SoftDeletes trait

Migration Setup

Use the auditableWithDeletes() blueprint macro:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->auditableWithDeletes();
$table->timestamps();
$table->softDeletes();
});
}
 
public function down(): void
{
Schema::dropIfExists('posts');
}
};

Model Setup

namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Yajra\Auditable\AuditableWithDeletesTrait;
 
class Post extends Model
{
use AuditableWithDeletesTrait;
use SoftDeletes;
}

Usage

The trait automatically records the authenticated user's ID when a record is deleted:

$post = Post::find(1);
$post->delete(); // Sets deleted_by to current user ID
 
// Restore the record (clears deleted_by)
Post::withTrashed()->find(1)->restore();

Accessing the Deleter

$post = Post::withTrashed()->first();
$deleter = $post->deleter;
 
echo $deleter->name; // "Admin User"
echo $post->deleted_by_name; // "Admin User"

How It Works

The AuditableWithDeletesTraitObserver hooks into:

  • Deleting: Sets deleted_by to the authenticated user's ID
  • Restoring: Clears deleted_by to null
// Deleting event
public function deleting(Model $model): void
{
$model->deleted_by = $this->getAuthenticatedUserId();
$model->saveQuietly();
}
 
// Restoring event
public function restoring(Model $model): void
{
$model->deleted_by = null;
}

::: tip Related API Methods The deleter() relationship and deleted_by_name accessor are defined in AuditableTrait. See the Auditable Trait API for complete documentation. :::