Search code examples
phplaravellaravel-5laravel-seeding

Is it possible to prevent Laravel running Model Events when the database is being Seeded?


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?


Solution

  • 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 ...
        }
    }