Calling Laravel seeders from migrations

Published under Laravel.

📺  Click here to skip to the video attached to this post  👇

Seeders in the Laravel framework allow you to populate your database with fake/seeded data. As you probably know, you can call a seeder from within a migration using Laravel. This technique is used when you have data in your database that is critical to your codebase, like permissions. Permissions are referenced in your codebase, so they must exist in your database at all times as well.

Here's an example of how you would call a seeder from a migration:

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:

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:

Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0