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

Eloquent.changelog Laravel Package

nebo15/eloquent.changelog

Laravel package that adds changelog/history tracking to Eloquent models. Record changes to attributes and keep an audit trail you can query later, useful for debugging, compliance, and reviewing edits over time.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nebo15/eloquent-changelog
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Nebo15\EloquentChangelog\EloquentChangelogServiceProvider::class,
    ],
    
  2. Publish Config:

    php artisan vendor:publish --provider="Nebo15\EloquentChangelog\EloquentChangelogServiceProvider"
    

    Configure config/eloquent-changelog.php (default: audit_table = changelogs).

  3. First Use Case: Enable changelogging for a model:

    use Nebo15\EloquentChangelog\ChangelogTrait;
    
    class User extends Model
    {
        use ChangelogTrait;
    }
    

    Now, any changes to User (create/update/delete) will be logged to the changelogs table.


Implementation Patterns

Core Workflows

  1. Automatic Logging:

    • The trait (ChangelogTrait) hooks into Eloquent’s lifecycle events (creating, updating, deleting, saved, restored).
    • Example: Track field-level changes:
      $user = User::find(1);
      $user->name = "Updated Name"; // Change logged automatically.
      $user->save();
      
  2. Manual Logging:

    • Force a log entry for a specific change:
      $user->logChange('email', 'old@example.com', 'new@example.com');
      
  3. Querying Changes:

    • Fetch changelog entries for a model:
      $changes = User::changelog()->where('user_id', 1)->get();
      
    • Filter by field, action type, or timestamp:
      $emailChanges = User::changelog()
          ->where('field', 'email')
          ->where('action', 'update')
          ->latest()
          ->get();
      
  4. Integration with Observers:

    • Use observers to log custom business logic changes:
      class UserObserver
      {
          public function logging($model)
          {
              $model->logChange('status', 'inactive', 'active', ['reason' => 'manual_activation']);
          }
      }
      
  5. Soft Deletes:

    • Enable soft deletes in the changelog model (Changelog) to track restores:
      class Changelog extends Model
      {
          use SoftDeletes;
          protected $dates = ['deleted_at'];
      }
      

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Each change triggers a database insert. For high-frequency models, consider:
      • Batch logging (e.g., queue delayed jobs).
      • Disabling changelogging for non-critical models:
        class Product extends Model
        {
            use ChangelogTrait;
            protected $changelogEnabled = false; // Disable for bulk operations.
        }
        
  2. Missing Fields in Logs:

    • Ensure old_values and new_values are serialized correctly. Override the trait’s getChangelogData() method if custom logic is needed:
      protected function getChangelogData()
      {
          return [
              'old_values' => json_encode($this->getOriginal()),
              'new_values' => json_encode($this->attributesToArray()),
          ];
      }
      
  3. Timestamp Precision:

    • The changelog uses created_at for timestamps. For auditing, ensure your server’s timezone is consistent (config/app.php).
  4. Foreign Key Constraints:

    • If the changelogs table references a non-existent model ID, logs will fail silently. Validate IDs before logging:
      if ($this->exists) {
          $this->logChange('field', 'old', 'new');
      }
      

Debugging

  1. Check Logged Data:

    • Inspect the changelogs table directly or dump the changelog model:
      dd(User::changelog()->first());
      
  2. Event Debugging:

    • Temporarily add a listener to debug hooks:
      Event::listen('eloquent.saving: User', function ($model) {
          logger()->debug('Saving user:', $model->toArray());
      });
      
  3. Migration Issues:

    • If the changelogs table isn’t created, run:
      php artisan vendor:publish --provider="Nebo15\EloquentChangelog\EloquentChangelogServiceProvider" --tag=migrations
      php artisan migrate
      

Extension Points

  1. Custom Changelog Model:

    • Extend the Changelog model to add fields (e.g., user_id for the auditor):
      class CustomChangelog extends \Nebo15\EloquentChangelog\Changelog
      {
          protected $fillable = ['user_id', 'ip_address'];
      }
      
    • Update the config to use your model:
      'model' => \App\Models\CustomChangelog::class,
      
  2. Prevent Logging for Specific Fields:

    • Override getChangelogIgnoreFields():
      protected function getChangelogIgnoreFields()
      {
          return ['password', 'remember_token'];
      }
      
  3. Add Metadata:

    • Pass additional data to logs via the logChange method:
      $user->logChange('status', 'pending', 'approved', [
          'auditor_id' => auth()->id(),
          'notes' => 'Approved via admin panel',
      ]);
      
    • Access metadata in queries:
      $changes = User::changelog()
          ->whereJsonContains('metadata->notes', 'Approved')
          ->get();
      
  4. Soft Deletes for Models:

    • If your model uses soft deletes, ensure the changelog captures deleted_at:
      $user->delete(); // Logs the deletion.
      $user->restore(); // Logs the restore if the Changelog model also uses SoftDeletes.
      
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