Owen Conti

Calling Laravel Seeders from Migrations

January 05, 2019 - ⌚ ~1 minute to read


As you probably know, you can call a seeder from within a migration using the Laravel framework. Here’s an example of how you would do that:

// inside migration file
public function up()
{
    // Create a table here

    // Call seeder
    Artisan::call('db:seed', [
        '--class' => 'SampleDataSeeder'
    ]);
}

Whenever your application is migrated and the above migration is run, the SampleDataSeeder will also run.

🚨🚨 There’s a catch! 🚨🚨

This will work fine in our local environment, however when we deploy this to production, the seeder will fail to run. Assuming our APP_ENV environment variable value is PRODUCTION, we need to tell Laravel that we acknowledge we are running this in production:

php artisan migration --force

We also need to do the same thing when running the seeder from within the migration. When it comes down to it, all we’re doing is invoking another Artisan command, which has its own set of flags. So to make sure our seeder works in production, pass the --force flag when calling the seeder:

// inside migration file
public function up()
{
    // Create a table here

    // Call seeder
    Artisan::call('db:seed', [
        '--class' => 'SampleDataSeeder',
        '--force' => true
    ]);
}
Tags: laravel php tips 

👋 Hi! If you enjoyed this post, consider following me on Twitter: @owenconti!