Installation:
composer require wildside/userstamps
Ensure your Laravel version is 9+ and PHP is 8.2+.
Database Migration: Add the columns to your model’s migration using the helper methods:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->userstamps(); // Adds `created_by`, `updated_by`
$table->timestamps();
});
For UUIDs:
$table->userstampsUuid();
Apply the Trait:
Add HasUserstamps to your Eloquent model:
use Wildside\Userstamps\HasUserstamps;
class Post extends Model
{
use HasUserstamps;
}
First Use Case:
Create a record—created_by and updated_by will auto-populate with the authenticated user’s ID:
$post = Post::create(['title' => 'Hello World']);
// $post->created_by === auth()->id();
Automatic User Tracking:
created_by/updated_by on create()/update().$post->createdBy->name; // Access related user
Soft Deletes Integration:
deleted_by via migration:
$table->userstampSoftDeletes();
$post->delete(); // $post->deleted_by === auth()->id();
Customizing User Resolution:
class Post extends Model
{
use HasUserstamps;
protected function getUserstampUser()
{
return User::findOrFail(123); // Force a specific user
}
}
Query Scopes:
Post::createdBy(User::first())->get();
Post::updatedBy(User::first())->get();
API/Queue Jobs:
auth() in jobs).auth middleware to ensure created_by/updated_by are set only for logged-in users.$this->actingAs($user)->post('/posts', ['title' => 'Test']);
morphTo for multi-model tracking:
$table->morphs('userstampable');
Missing Authentication:
created_by/updated_by will be null. Handle this in your logic or set a default user:
protected function getUserstampUser()
{
return auth()->check() ? auth()->user() : User::DEFAULT_SYSTEM_USER;
}
Column Type Mismatch:
created_by/updated_by match your users.id column type (e.g., unsignedBigInteger for bigIncrements()).Soft Deletes Conflicts:
SoftDeletes, ensure deleted_at and deleted_by are both present. The package won’t add deleted_at—use SoftDeletes trait separately.UUIDs:
userstampsUuid() but ensure your users.id is a UUID column (e.g., Uuid type in Laravel).getUserstampUser() returns the expected user:
dd($model->getUserstampUser());
php artisan migrate:fresh if column types are incorrect.Custom Columns:
Override getUserstampColumns() to use non-standard column names:
protected function getUserstampColumns()
{
return ['author_id', 'editor_id'];
}
Event Hooks:
Listen for userstamp.created/userstamp.updated events to trigger side effects:
event(new PostCreated($post));
Batch Operations:
The package doesn’t auto-fill during insert() or update() queries. Use model instances or manual assignment for bulk operations:
Post::insert([...]); // Won't auto-set userstamps
How can I help you explore Laravel packages today?