Calling Laravel Seeders from Migrations | Owen Conti

Calling Laravel Seeders from Migrations

Published on Jan 05, 2019 in category Laravel.

๐Ÿ‘‹There's a video version of this post at the bottom of the page.

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
    ]);
}


Thanks for reading!

๐Ÿ‘‹ Hi there! I hope you enjoyed this post. If you did, follow me on Twitter, @owenconti, for updates on new posts.

If you prefer to receive updates via email, subscribe to my newsletter where I send a weekly summary of the content I've released.

Feel free to check out other posts in the Laravel category.