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 Column Watcher Laravel Package

ascend/laravel-column-watcher

Attribute-based “column watchers” for Laravel Eloquent models. Trigger handlers only when specific attributes change (before/after save), with support for multiple watchers, queueable handlers, events, and Octane compatibility—avoiding bulky, monolithic model observers.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Granular Event Handling: The package excels in scenarios requiring fine-grained control over Eloquent model column changes, reducing boilerplate compared to traditional observers. Ideal for:
    • Audit Logging: Track specific column modifications (e.g., updated_at, custom metadata).
    • Business Logic Triggers: Execute logic only when critical columns (e.g., status, price) change.
    • Real-Time Notifications: Dispatch events (e.g., via Laravel Echo) when watched columns are updated.
  • Observer Replacement: Replaces broad-scope observers with targeted column-level handlers, improving maintainability in large codebases.
  • PHP 8 Attributes: Leverages modern PHP features for cleaner, type-safe annotations.

Integration Feasibility

  • Laravel Eloquent Dependency: Tightly coupled to Eloquent models; requires existing Laravel projects using Eloquent ORM.
  • Attribute-Based: Minimal runtime overhead during model initialization (attributes are parsed once).
  • Queue Support: Async handlers reduce latency for I/O-bound operations (e.g., API calls, database writes).
  • Timing Control: beforeSave/afterSave hooks enable pre-validation or post-processing logic.

Technical Risk

  • PHP 8.2+ Requirement: May block adoption in legacy PHP stacks (though Laravel 11+ aligns with this).
  • Attribute Reflection: Relies on runtime attribute parsing; could introduce subtle bugs if misconfigured (e.g., circular dependencies in handlers).
  • Infinite Loop Protection: Built-in, but custom handlers must avoid recursive triggers (e.g., updating the same column in a handler).
  • Testing Overhead: Column-specific tests may need updates if watched columns or handlers change.

Key Questions

  1. Use Case Alignment:
    • Are we replacing observers or supplementing them? If replacing, what’s the scope of existing observer logic?
    • Do we need cross-column validation (e.g., "if price changes, ensure tax_rate is valid")? This package handles single-column triggers.
  2. Performance:
    • How many models/columns will be watched? High-volume models may benefit from lazy-loading handlers.
    • What’s the cost of afterSave queue jobs vs. synchronous handlers?
  3. Error Handling:
    • How will failed handlers be retried/logged? (Leverage Laravel’s queue failure channels.)
    • Are there transaction boundaries to consider? (e.g., rolling back on handler failure.)
  4. Migration Path:
    • Can existing observers be incrementally replaced with column watchers?
    • How will we handle legacy code that hooks into saved()/updating() events?
  5. Testing:
    • How will we test column-specific logic? Mocking ColumnChange objects may be necessary.
    • Are there edge cases (e.g., mass assignments, soft deletes) to validate?

Integration Approach

Stack Fit

  • Laravel 11/12/13: Native support; no framework modifications needed.
  • PHP 8.2+: Required for attributes; aligns with Laravel’s modern stack.
  • Queue Systems: Supports database/Redis queues for async handlers (e.g., afterSave).
  • Testing Tools: Works with Pest/PHPUnit (148 passing tests in repo).
  • Monitoring: Integrates with Laravel’s logging and queue monitoring (e.g., Horizon).

Migration Path

  1. Assessment Phase:
    • Audit existing observers for column-specific logic. Identify candidates for replacement.
    • Document observer → watcher migration rules (e.g., observing(User::class)[User::class, 'email']).
  2. Incremental Rollout:
    • Start with non-critical observers (e.g., analytics logging).
    • Replace one observer at a time, verifying no regressions.
  3. Handler Conversion:
    • Before: UserObserver::updating(User $user)After:
      #[Watcher(columns: ['email'])]
      class UpdateEmailHandler {
          public function handle(ColumnChange $change): void { ... }
      }
      
    • Use #[Watcher(timing: Timing::BEFORE_SAVE)] for pre-processing.
  4. Legacy Support:
    • Keep observers for global logic (e.g., deleting()) until fully migrated.
    • Use Laravel’s event system to bridge observers and watchers if needed.

Compatibility

  • Eloquent Models: Works with standard models, polymorphic relations, and soft deletes.
  • Custom Accessors/Mutators: Handlers receive raw column values; mutators run before watchers.
  • API Resources: No direct impact, but watchers can trigger resource updates (e.g., cache invalidation).
  • Third-Party Packages: May conflict if they also hook into saving()/updating(). Test with:
    • Laravel Nova/Forge.
    • Spatie Media Library (if watching file columns).
    • Cashier/Paddle (for subscription status changes).

Sequencing

  1. Development:
    • Add package via Composer: composer require ascend/laravel-column-watcher.
    • Configure in config/app.php (autoloads attributes).
  2. Testing:
    • Write unit tests for handlers using ColumnChange mocks.
    • Test edge cases: concurrent updates, mass assignments, nested transactions.
  3. Deployment:
    • Roll out in stages (e.g., staging → production).
    • Monitor queue job failures (e.g., failed_jobs table).
  4. Post-Launch:
    • Add monitoring for handler execution time/errors.
    • Document new patterns for onboarding teams.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Handlers are co-located with models (e.g., app/Models/User/Handlers/).
    • Self-Documenting: Attributes clearly declare watched columns.
    • Isolated Logic: Easier to refactor individual handlers vs. monolithic observers.
  • Cons:
    • Attribute Management: Adding/removing watchers requires code changes (vs. config-based observers).
    • Handler Discovery: May need custom logic to list all watched columns (e.g., for admin panels).

Support

  • Debugging:
    • Use dd($change) in handlers to inspect ColumnChange objects (old/new values, model instance).
    • Leverage Laravel’s tap() for debugging:
      $change->tap(fn($c) => tap($c->model)->forceFill(['debug' => true]));
      
  • Common Issues:
    • Infinite Loops: Ensure handlers don’t trigger watched column updates (e.g., user->update(['email' => $change->newValue])).
    • Queue Stuck Jobs: Monitor failed_jobs for handler exceptions.
  • Documentation:
    • Maintain a runbook for:
      • Handler failure modes.
      • Column watcher vs. observer tradeoffs.
      • Example ColumnChange payloads.

Scaling

  • Performance:
    • Attribute Parsing: Minimal overhead (one-time per model class).
    • Handler Execution: Async handlers (queued) scale horizontally with Laravel queues.
    • Database Load: Avoid heavy operations in beforeSave handlers (use queues for afterSave).
  • High-Volume Models:
    • Consider lazy-loading handlers (e.g., only register watchers for active models).
    • Use queue batching for bulk updates (e.g., Model::where(...)->update()).
  • Cold Starts:
    • Handlers are loaded on-demand; no global performance impact.

Failure Modes

Failure Scenario Impact Mitigation
Handler throws exception Transaction rollback (if in beforeSave). Use try-catch in handlers; log errors.
Queue worker crashes Async handlers fail silently. Enable queue monitoring (Horizon).
Circular dependency Infinite loop on column updates. Add #[Watcher(protection: true)] (built-in).
Attribute parsing error Model initialization fails. Validate PHP version/attributes in CI.
Mass assignment bypasses watch Unwatched columns updated. Use $model->fill() instead of update().

Ramp-Up

  • Onboarding:
    • For Developers:
      • Train on attribute syntax and ColumnChange object structure.
      • Provide templates for common handlers (e.g., audit logging, notifications).
    • For QA:
      • Emphasize testing beforeSave/afterSave timing and edge cases.
  • Documentation Gaps:
    • Add examples for:
      • Complex Logic: Combining multiple columns (e.g., if (price > 1000 && status === 'active')).
      • Dynamic Watchers: Conditionally enabling/disabling watchers (e.g., based on model state).
  • Tooling:
    • Create a CLI command to list all watched columns/models:
      php artisan column-watcher:list
      
    • Integrate with **
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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