Posted on under Laravel by Owen Conti.
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:
1<?php 2 3// inside migration file 4public function up() 5{ 6 // Create a table here 7 8 // Call seeder 9 Artisan::call('db:seed', [10 '--class' => 'SampleDataSeeder',11 ]);12}
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:
1php 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:
1<?php 2 3// inside migration file 4public function up() 5{ 6 // Create a table here 7 8 // Call seeder 9 Artisan::call('db:seed', [10 '--class' => 'SampleDataSeeder',11 '--force' => true // <--- add this line12 ]);13}
Hopefully you found this article useful! If you did, share it on X!
Found an issue with the article? Submit your edits against the repository.