Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Doctrine Timestamp Laravel Package

ursusarctosua/doctrine-timestamp

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ursusarctosua/doctrine-timestamp
    

    Add the service provider to config/app.php under providers:

    UrsusArctosUA\DoctrineTimestamp\DoctrineTimestampServiceProvider::class,
    
  2. Publish Config

    php artisan vendor:publish --provider="UrsusArctosUA\DoctrineTimestamp\DoctrineTimestampServiceProvider" --tag="config"
    

    Configure config/doctrine-timestamp.php (default values provided).

  3. 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).


Implementation Patterns

Workflows

  1. Basic Usage

    • No extra code needed; timestamps auto-manage on create()/update().
    • Override defaults via model attributes:
      class Post extends Model
      {
          use Timestampable;
      
          protected $timestampFormat = 'Y-m-d H:i:s.uP'; // Custom format
      }
      
  2. Custom Fields

    • Use protected $timestampable = ['custom_created_at', 'custom_updated_at'] to override field names.
  3. Manual Updates

    • Force timestamp updates:
      $user->touch(); // Updates `updated_at`
      $user->freshTimestamp(); // Resets `created_at` to now
      
  4. Doctrine Integration

    • If using Doctrine ORM alongside Eloquent, configure the provider to sync formats:
      'doctrine_sync' => true, // In config/doctrine-timestamp.php
      

Integration Tips

  • Migrations: Use timestamps() in migrations for consistency:
    Schema::create('users', function (Blueprint $table) {
        $table->timestamps(); // Uses DoctrineTimestamp defaults
    });
    
  • API Responses: Normalize timestamps in API resources:
    public function toArray($request)
    {
        return [
            'created_at' => $this->created_at->format('Y-m-d\TH:i:s.uP'),
            // ...
        ];
    }
    
  • Testing: Mock timestamps in unit tests:
    use UrsusArctosUA\DoctrineTimestamp\Facades\DoctrineTimestamp;
    
    $this->beforeApplicationDestroy(function () {
        DoctrineTimestamp::shouldReceive('now')->andReturn(Carbon::now());
    });
    

Gotchas and Tips

Pitfalls

  1. Timezone Conflicts

    • Ensure config/app.php timezone matches DoctrineTimestamp’s default (UTC by default).
    • Override in model:
      protected $timestampTimezone = 'Europe/Berlin';
      
  2. Precision Loss

    • MySQL DATETIME fields truncate microseconds. Use TIMESTAMP or DATETIME(6) for full precision.
  3. Caching Quirks

    • If using model caching (e.g., remember()), timestamps may not update. Disable caching or refresh manually:
      $user->refreshFromDatabase();
      
  4. Doctrine ORM Clashes

    • If using both Eloquent and Doctrine ORM, ensure the DoctrineTimestamp provider loads after Doctrine’s lifecycle callbacks.

Debugging

  • 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).

Extension Points

  1. Custom Timestamp Logic Override getTimestamp() in your model:

    protected function getTimestamp($field)
    {
        return Carbon::now()->startOfHour(); // Round to hour
    }
    
  2. Event Hooks Listen for timestamp events:

    DoctrineTimestamp::listen('beforeSave', function ($model) {
        if ($model instanceof User) {
            $model->custom_updated_at = now();
        }
    });
    
  3. 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);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky