27

Laravel's seeder runs a variety of Model Events on my models which trigger New Order notification emails, among other things, from the Product::saved() Model Event.

This significantly slows down database seeding. Is it possible to detect whether a Seed is being ran and if so, tell Laravel not to run the Model Events?

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
Jack
  • 9,615
  • 18
  • 72
  • 112

3 Answers3

37

There are functions on the Model class which will allow you to ignore events.

Before using a model to seed, you will need to do something like this...

YourModel::flushEventListeners();
user1669496
  • 32,176
  • 9
  • 73
  • 65
27

I recommend to remove the Dispatcher in this Case from the Eloquent Model.

For example.

// Check Dispatcher
Model::getEventDispatcher()

// Remove Dispatcher
Model::unsetEventDispatcher()

// Add Dispatcher
Model::setEventDispatcher(new \Illuminate\Events\Dispatcher);
thisisablock
  • 549
  • 3
  • 6
3

Add WithoutModelEvents Trait to your seeder

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    public function run(): void
    {
        // Silent eloquent queries ...
    }
}
medilies
  • 1,811
  • 1
  • 8
  • 32