![]()
WARNING You're browsing the documentation for an upcoming version of Laravel Auditable. The documentation and features of this release are subject to change.
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
- Add the
deleted_bycolumn to your table - Use
AuditableWithDeletesTraiton your model - Use Laravel's
SoftDeletestrait
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_byto the authenticated user's ID - Restoring: Clears
deleted_bytonull
// Deleting eventpublic function deleting(Model $model): void{ $model->deleted_by = $this->getAuthenticatedUserId(); $model->saveQuietly();} // Restoring eventpublic 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.
:::