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

Laravel Auditable Uuid Laravel Package

zitech/laravel-auditable-uuid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require zitech/laravel-auditable-uuid to add the package to your project.

  2. Publish Configuration Execute php artisan vendor:publish --provider="Zitech\LaravelAuditableUuid\LaravelAuditableUuidServiceProvider" to publish the ziAuditable.php config file. Set 'useUuid' => true to enable UUID support.

  3. Migration Setup Add ->auditable() to your model's migration schema (e.g., users table):

    Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('name', 100);
        $table->auditable(); // <-- Add this line
        $table->timestamps();
    });
    
  4. Model Integration Use the AuditableTrait in your model (e.g., User):

    use Zitech\LaravelAuditableUuid\AuditableTrait;
    
    class User extends Model {
        use AuditableTrait;
        public $incrementing = false; // Required for UUID models
    }
    
  5. Run Migrations Execute php artisan migrate to apply the changes.

First Use Case

After setup, the package automatically creates an audits table for tracking changes to your model. Test by creating/updating a User record:

$user = User::create(['name' => 'John Doe']);
$user->update(['name' => 'Jane Doe']);

// Check audits
$audits = $user->audits; // Returns a collection of audit records

Implementation Patterns

Workflows

  1. Audit Tracking

    • The package automatically logs created_at, updated_at, deleted_at, and created_by, updated_by, deleted_by fields (if configured) for all model changes.
    • Example: Track who created/updated a record:
      $user = User::find(1);
      $user->audits->last()->created_by; // Returns the user ID of the last update
      
  2. Custom Audit Fields

    • Extend the AuditableTrait to add custom audit columns:
      use Zitech\LaravelAuditableUuid\Concerns\HasCustomAuditableFields;
      
      class User extends Model {
          use AuditableTrait, HasCustomAuditableFields;
      
          protected $customAuditableFields = ['status', 'role'];
      }
      
  3. Soft Deletes with Audits

    • Enable soft deletes in your model and ensure the deleted_at field is audited:
      use SoftDeletes;
      
      class User extends Model {
          use AuditableTrait, SoftDeletes;
      }
      
  4. Querying Audits

    • Filter audits by event type (e.g., created, updated):
      $user = User::find(1);
      $createdAudits = $user->audits()->where('event', 'created')->get();
      

Integration Tips

  • UUID Models: Always set public $incrementing = false in models using UUIDs to avoid conflicts with auto-incrementing IDs.
  • Foreign Keys: If audits reference users, ensure the created_by/updated_by columns are foreign keys:
    Schema::table('audits', function (Blueprint $table) {
        $table->foreign('created_by')->references('id')->on('users');
    });
    
  • Batch Operations: Use withoutEvents() for bulk operations to avoid excessive audit logs:
    User::withoutEvents(function () {
        User::where('status', 'inactive')->update(['status' => 'active']);
    });
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • If you add ->auditable() to an existing table, the package will attempt to add columns without dropping the table. Solution: Drop and recreate the table or manually add the columns:
      Schema::table('users', function (Blueprint $table) {
          $table->dropAuditable(); // Remove existing audit columns
      });
      Schema::table('users', function (Blueprint $table) {
          $table->auditable(); // Re-add
      });
      
  2. UUID Collisions

    • UUIDs are globally unique, but if you manually set IDs, ensure they are valid UUIDs (e.g., Ramsey\Uuid\Uuid::uuid4()). Solution: Validate UUIDs in model boot methods:
      protected static function boot() {
          parent::boot();
          static::creating(function ($model) {
              if (!$model->id || !Str::isUuid($model->id)) {
                  $model->id = Str::uuid()->toString();
              }
          });
      }
      
  3. Performance Overhead

    • Auditing every change can slow down writes. Solution: Disable auditing for specific operations:
      User::withoutAuditing(function () {
          User::create(['name' => 'Bulk User']);
      });
      
  4. Missing Config

    • Forgetting to set 'useUuid' => true in ziAuditable.php will cause the package to use auto-incrementing IDs for audits. Solution: Always verify the config after publishing.

Debugging

  • Audit Logs Not Appearing:

    • Check if the audits table exists and has the correct columns (model_id, event, old_values, new_values, etc.).
    • Verify the model uses AuditableTrait and $incrementing = false.
    • Ensure the created_by/updated_by fields are populated (e.g., via middleware or model observers).
  • UUID Errors:

    • If you see SQLSTATE[23000] errors, it’s likely due to invalid UUIDs. Use DB::statement("SET sql_mode='NO_AUTO_VALUE_ON_ZERO';") in a migration if needed.

Extension Points

  1. Custom Audit Events Override the getAuditableEvent() method in your model to customize audit events:

    public function getAuditableEvent()
    {
        return $this->wasRecentlyCreated ? 'created' : 'updated_custom';
    }
    
  2. Audit Table Naming Change the default audits table name by publishing the config and setting 'table' => 'custom_audit_table'.

  3. Excluding Fields Prevent specific fields from being audited:

    class User extends Model {
        use AuditableTrait;
    
        protected $auditableExcludes = ['password', 'api_token'];
    }
    
  4. Custom Audit Columns Add extra columns to the audits table by extending the AuditableTrait:

    use Zitech\LaravelAuditableUuid\Concerns\HasExtraAuditableColumns;
    
    class User extends Model {
        use AuditableTrait, HasExtraAuditableColumns;
    
        protected $extraAuditableColumns = ['ip_address', 'user_agent'];
    }
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours