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

Ignorable Observers Laravel Package

zachflower/ignorable-observers

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require zachflower/ignorable-observers
    
  2. Add Trait: Include IgnorableObservers in your Eloquent model:
    use IgnorableObservers\IgnorableObservers;
    
    class User extends Model {
        use IgnorableObservers;
    }
    
  3. First Use Case: Disable observers for bulk operations:
    User::ignoreObservableEvents(); // Disables all observers
    User::createMany($users); // No observers triggered
    User::resumeObservableEvents(); // Re-enables observers
    

Where to Look First

  • Trait Methods: Focus on ignoreObservableEvents(), resumeObservableEvents(), and ignoreObservableEventsFor() (for selective disabling).
  • Thread Safety: Check ignoreObservableEventsForThread() for async/queue operations.
  • Testing: Use isIgnoringObservableEvents() to verify state in tests.

Implementation Patterns

Common Workflows

  1. Bulk Operations:

    User::ignoreObservableEvents();
    try {
        User::insert($batchData);
        // No emails, notifications, or queued jobs triggered
    } finally {
        User::resumeObservableEvents();
    }
    
  2. Selective Observer Disabling:

    User::ignoreObservableEventsFor([UserObserver::class]);
    // Only UserObserver is ignored; other observers run normally
    
  3. Thread-Specific Ignoring (for queues/jobs):

    User::ignoreObservableEventsForThread();
    // Observers ignored only in this thread
    
  4. Conditional Disabling (e.g., in API routes):

    if ($request->hasHeader('X-Ignore-Observers')) {
        User::ignoreObservableEvents();
    }
    

Integration Tips

  • Middleware: Create middleware to toggle observers based on request headers/flags.
  • Service Layer: Wrap bulk operations in a service class to ensure resumeObservableEvents() is always called.
  • Testing: Use isIgnoringObservableEvents() in tests to assert observer behavior:
    $this->assertTrue(User::isIgnoringObservableEvents());
    

Gotchas and Tips

Pitfalls

  1. Forgetting to Resume:

    • Observers remain disabled if resumeObservableEvents() is omitted. Use try-finally blocks or service wrappers.
    • Fix: Create a helper method:
      function withIgnoredObservers(callable $callback) {
          User::ignoreObservableEvents();
          try {
              $callback();
          } finally {
              User::resumeObservableEvents();
          }
      }
      
  2. Thread Leaks:

    • ignoreObservableEventsForThread() only affects the current thread. Queued jobs may not inherit the state.
    • Fix: Explicitly call ignoreObservableEventsForThread() in job constructors if needed.
  3. Observer Registration Timing:

    • Observers must be registered before ignoreObservableEvents() is called, or they won’t be ignored.
    • Fix: Register observers in a service provider’s boot() method.
  4. Static Method Limitation:

    • The trait uses static methods, which may not work well with dependency injection or polymorphic models.
    • Workaround: Extend the trait or use a facade for dynamic model handling.

Debugging

  • Check State:
    \Log::debug('Observers ignored?', [User::isIgnoringObservableEvents()]);
    
  • Observer Logs: Add debug logs in your observers to verify they’re being skipped:
    public function creating(Model $model) {
        \Log::debug('Creating observer triggered?', [$model->exists]);
    }
    

Extension Points

  1. Custom Ignore Logic: Override the trait’s ignoreObservableEvents() to add conditions:

    public static function ignoreObservableEvents() {
        if (!app()->environment('production')) {
            return; // Skip in non-prod
        }
        parent::ignoreObservableEvents();
    }
    
  2. Global Toggle: Create a singleton service to manage global observer states across models:

    class ObserverManager {
        protected static $globalIgnore = false;
    
        public static function ignoreGlobally() {
            self::$globalIgnore = true;
        }
    }
    

    Then modify the trait to respect this flag.

  3. Observer Whitelisting: Extend the trait to allow whitelisting observers instead of blacklisting:

    public static function ignoreAllBut(array $observers) {
        // Implementation...
    }
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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