akaunting / laravel-mutable-observer
Mutable observer package for Laravel
Package info
github.com/akaunting/laravel-mutable-observer
pkg:composer/akaunting/laravel-mutable-observer
Requires
- php: ^8.2
- laravel/framework: ^10.30|^11.0|^12.0|^13.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- larastan/larastan: ^3.0
- orchestra/testbench: ^8.0|^9.0|^10.0|^11.0
- phpunit/phpunit: ^10.5|^11.5|^12.5|^13.0
- psalm/plugin-laravel: ^3.0|^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 21:33:30 UTC
README
This package allows you to mute and unmute specific observer events at will. It ships with a trait that adds mutable methods to your observer classes, making it perfect for testing scenarios and preventing unwanted side effects.
Features
- ✅ Mute all events or specific ones - and unmute them one by one
- ✅ Scoped muting -
withoutEvents()restores the previous state when the callback ends, even on exceptions - ✅ Typo-safe - naming an event the observer does not have throws an exception
- ✅ Dependency injection friendly - observers with constructor dependencies can be muted
- ✅ Respects after-commit observers - unmuted events still wait for the transaction to commit
- ✅ Leaves the container as it found it - singletons and custom bindings survive unmuting
- ✅ Laravel 10.30+, 11, 12 and 13, PHP 8.2+
Installation
Run the following command:
composer require akaunting/laravel-mutable-observer
Usage
Basic Setup
Add the Mutable trait to your observer class:
namespace App\Observers; use Akaunting\MutableObserver\Traits\Mutable; class UserObserver { use Mutable; public function creating($user) { // Validate or fill in attributes } public function created($user) { Mail::to($user->email)->send(new WelcomeEmail($user)); } public function updated($user) { Log::info("User updated: {$user->email}"); } }
Event names are the observer's method names (created, updating, forceDeleted, ...). They are matched case-insensitively.
Muting for the Duration of a Callback
The safest way to mute: the previous state comes back when the callback ends, even if it throws.
// Every event of the observer $user = UserObserver::withoutEvents(fn () => User::create($data)); // Only some events: no welcome email, everything else runs $user = UserObserver::withoutEvents(fn () => User::create($data), 'created');
The callback's return value is passed through. Calls can be nested, and whatever was muted before the call stays muted after it.
Muting and Unmuting by Hand
UserObserver::mute(); // every event UserObserver::mute('created'); // one event UserObserver::mute(['created', 'updated']); // several events UserObserver::unmute(); // every event: the observer is back to normal UserObserver::unmute('created'); // only this event
Muting adds to what is already muted:
UserObserver::mute('created'); UserObserver::mute('updated'); // created and updated are both muted
Unmuting one event of a fully muted observer leaves everything else muted:
UserObserver::mute(); UserObserver::unmute('created'); // every event is muted except created
Checking What Is Muted
UserObserver::isMuted(); // is any event muted? UserObserver::isMuted('created'); // is this event muted?
Catching Typos
Naming an event the observer has no method for throws an InvalidArgumentException, instead of silently muting nothing:
UserObserver::mute('craeted'); // InvalidArgumentException: Observer [App\Observers\UserObserver] has no [craeted] method, ...
Real-World Examples
Tests
Laravel builds a fresh application for every test, so a mute never leaks into the next test:
public function test_user_can_be_created_without_side_effects(): void { UserObserver::mute(); $user = User::factory()->create(); $this->assertDatabaseHas('users', ['email' => $user->email]); } public function test_no_welcome_email_is_sent_on_import(): void { Mail::fake(); UserObserver::withoutEvents(fn () => User::factory()->count(10)->create(), 'created'); Mail::assertNothingSent(); }
Imports
UserObserver::withoutEvents(function () use ($rows) { foreach ($rows as $row) { User::create($row); } });
Query builder methods such as
User::insert()never fire model events, so they need no muting.
Resetting Everything
In long-running processes, such as Octane workers or queue workers, unmute every observer at once:
use Akaunting\MutableObserver\ProxyManager; app(ProxyManager::class)->unmuteAll();
API Reference
All methods are static methods added to your observer by the Mutable trait. $events is an event name, an array of event names, or null for all events.
| Method | Description |
|---|---|
mute(string|array|null $events = null): void |
Mutes the events, in addition to those already muted. |
unmute(string|array|null $events = null): void |
Unmutes the events. Once nothing is muted, the container is restored to what it held before (a singleton keeps its instance, a custom binding keeps working). Does nothing if the observer is not muted. |
isMuted(?string $event = null): bool |
Whether any event is muted, or whether the given event is. |
withoutEvents(callable $callback, string|array|null $events = null): mixed |
Runs the callback with the events muted, then restores the previous state, even if the callback throws. Returns the callback's result. |
WILDCARD_EVENT |
The constant '*', which stands for every event. |
mute(), unmute(), isMuted() and withoutEvents() throw an InvalidArgumentException for an event the observer has no method for.
ProxyManager::unmuteAll() unmutes every observer.
Requirements
- PHP 8.2 or higher (8.3 or higher for Laravel 13)
- Laravel 10.30 or higher, 11, 12 or 13
Upgrading from 3.x
- PHP 8.2 and Laravel 10.30 are now the minimum versions. Stay on 3.x (or 2.x) for older versions.
mute()adds to what is already muted. In 3.x,mute('created')followed bymute('updated')left onlyupdatedmuted; now both are muted. To replace, callunmute()first.- Unknown event names throw.
mute('craeted')used to mute nothing silently; it now throws anInvalidArgumentException. ProxyManager::register(object $target, array $events)andProxyManager::unregister(object $target)were replaced byProxyManager::mute(string $class, array $events)andProxyManager::unmute(string $class, ?array $events = null).Proxyis no longer bound in the container; the manager creates proxies itself. Its constructor takes aMuteStateinstead of an array of events.unmute()no longer leaves a shared instance of the observer behind in the container.
Code Quality
- ✅ PHPStan Level Max - Maximum static analysis level
- ✅ Psalm Level 1 - Strictest type checking
- ✅ PHP CS Fixer - PSR-12 compliant code style
- ✅ 100% Test Coverage - Unit tests plus end-to-end tests against real Eloquent models
- ✅ Strict Types - All files use
declare(strict_types=1)
Running Quality Checks
# Run all quality checks composer quality # Individual checks composer test # Run tests composer test:coverage # Run tests with coverage report composer analyse # Run PHPStan + Psalm composer phpstan # Run PHPStan only composer psalm # Run Psalm only composer format # Fix code style issues composer format:check # Check code style without fixing # Using Makefile (Unix/Mac/WSL) make quality # Run all quality checks make test # Run tests make analyse # Run static analysis make format # Fix code style make help # Show all available commands
How It Works
Laravel resolves an observer from the service container every time one of its events fires. When you mute an observer, the package resolves it (with its dependencies) and binds a proxy under the observer's class name. The proxy swallows the muted events and forwards everything else, including properties such as $afterCommit, to the real observer. When nothing is muted any more, the container is put back exactly as it was.
Limitations
- While an observer is muted, resolving it from the container (
app(UserObserver::class)) returns the proxy, not aUserObserverinstance. Code that type-hints the observer class itself will receive the proxy during that time. - Queued observers (
ShouldQueue) run in a queue worker, a separate process that does not see the mute. - The mute lives in the container. In long-running processes such as Octane or queue workers, prefer
withoutEvents(), or callProxyManager::unmuteAll()between jobs or requests.
Best Practices
- Prefer
withoutEvents()overmute()/unmute()pairs outside of tests: it cannot forget to unmute. - Be specific - mute only the events you need to silence:
withoutEvents($callback, 'created')rather than every event. - Say why - a short comment next to a mute saves the next reader a search:
// No welcome emails for imported users UserObserver::withoutEvents(fn () => $this->import($rows), 'created');
Troubleshooting
Q: Observer still firing after muting?
A: Make sure the observer is registered through Laravel's observer system (Model::observe() or #[ObservedBy]) and uses the Mutable trait. Queued observers (ShouldQueue) cannot be muted, see Limitations.
Q: Can I mute observers globally?
A: Yes, mute them in a service provider's boot() method or middleware.
Q: Does this work with model events?
A: Yes, it works with any observer registered via Model::observe() or the #[ObservedBy] attribute.
Changelog
Please see Releases for more information what has changed recently.
Contributing
Pull requests are more than welcome. You must follow the PSR coding standards.
Security
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see LICENSE for more information.