'Laravel. Disable observer methods if the database is seeding
I have an observer for my User model. Inside my observer->created event i have some code.
public function created(User $user)
{
sendEmail();
}
So, the idea is, when a user is created, the system will send for the user email notification that the account was created.
Question: When the database is seeding, it also calls this method 'created' and sends users (that are in the seeds) email notification. So, my question is, how can i check, probably inside this 'created' method if at the moment laravel is seeding data -> do not send email of do not run the 'created' observer method.
Tried to google, found something, but not working correct.
Something like YourModel::flushEventListeners();
Solution 1:[1]
You can use YourModel::unsetEventDispatcher(); to remove the event listeners for a model temporary.
If you need them after seeding in the same execution, you can read the dispatchers, unset them and then set them again.
$dispatcher = YourModel::getEventDispatcher()
// Remove Dispatcher
YourModel::unsetEventDispatcher();
// do stuff here
// Re-add Dispatcher
YourModel::setEventDispatcher($dispatcher);
Solution 2:[2]
namespace Database\Seeders;
use App\Models\Blog;
use Illuminate\Database\Seeder;
class BlogsTableSeeder extends Seeder
{
public function run()
{
Blog::withoutEvents(function () {
// normally
Blog::factory()
->times(10)
->hasUploads(1) //hasOne
->hasComments(2) //hasMany
->create();
});
}
}
Solution 3:[3]
You may mute event with WithoutModelEvents trait
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class SomeSeeder extends Seeder
{
use WithoutModelEvents;
public function run()
{
User::factory( 30 )->create();
}
}
or you may try createQuietly method of a factory, for example
class SomeSeeder extends Seeder
{
public function run()
{
User::factory( 30 )->createQuietly();
}
}
Solution 4:[4]
You could use the saveQuietly() function https://laravel.com/docs/8.x/eloquent#saving-a-single-model-without-events This allows you to disable all events for a single model.
If you wanna disable a single event for a single model, read about it here: http://derekmd.com/2019/02/conditionally-suppressing-laravel-event-listeners/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | julianstark999 |
| Solution 2 | Tjeu Moonen |
| Solution 3 | Ihar Aliakseyenka |
| Solution 4 | Musti |
