ursusarctosua/doctrine-timestamp
Installation
composer require ursusarctosua/doctrine-timestamp
Add the service provider to config/app.php under providers:
UrsusArctosUA\DoctrineTimestamp\DoctrineTimestampServiceProvider::class,
Publish Config
php artisan vendor:publish --provider="UrsusArctosUA\DoctrineTimestamp\DoctrineTimestampServiceProvider" --tag="config"
Configure config/doctrine-timestamp.php (default values provided).
First Use Case
Apply the trait to a model (e.g., User.php):
use UrsusArctosUA\DoctrineTimestamp\Traits\Timestampable;
class User extends Model
{
use Timestampable;
}
Now, created_at and updated_at will auto-populate with Doctrine-style timestamps (microsecond precision).
Basic Usage
create()/update().class Post extends Model
{
use Timestampable;
protected $timestampFormat = 'Y-m-d H:i:s.uP'; // Custom format
}
Custom Fields
protected $timestampable = ['custom_created_at', 'custom_updated_at'] to override field names.Manual Updates
$user->touch(); // Updates `updated_at`
$user->freshTimestamp(); // Resets `created_at` to now
Doctrine Integration
'doctrine_sync' => true, // In config/doctrine-timestamp.php
timestamps() in migrations for consistency:
Schema::create('users', function (Blueprint $table) {
$table->timestamps(); // Uses DoctrineTimestamp defaults
});
public function toArray($request)
{
return [
'created_at' => $this->created_at->format('Y-m-d\TH:i:s.uP'),
// ...
];
}
use UrsusArctosUA\DoctrineTimestamp\Facades\DoctrineTimestamp;
$this->beforeApplicationDestroy(function () {
DoctrineTimestamp::shouldReceive('now')->andReturn(Carbon::now());
});
Timezone Conflicts
config/app.php timezone matches DoctrineTimestamp’s default (UTC by default).protected $timestampTimezone = 'Europe/Berlin';
Precision Loss
DATETIME fields truncate microseconds. Use TIMESTAMP or DATETIME(6) for full precision.Caching Quirks
remember()), timestamps may not update. Disable caching or refresh manually:
$user->refreshFromDatabase();
Doctrine ORM Clashes
Log Timestamps: Enable debug mode in config:
'debug' => env('DOCTRINE_TIMESTAMP_DEBUG', false),
Logs timestamp operations to storage/logs/laravel.log.
Check Formats: Validate database column types match the configured format (e.g., DATETIME(6) for microseconds).
Custom Timestamp Logic
Override getTimestamp() in your model:
protected function getTimestamp($field)
{
return Carbon::now()->startOfHour(); // Round to hour
}
Event Hooks Listen for timestamp events:
DoctrineTimestamp::listen('beforeSave', function ($model) {
if ($model instanceof User) {
$model->custom_updated_at = now();
}
});
Database-Level Triggers For critical systems, combine with database triggers to ensure atomicity:
CREATE TRIGGER update_user_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
SET updated_at = NOW(6);
How can I help you explore Laravel packages today?