Is there something I can put in my migrations to automatically seed the table with test data once the migration has completed?
Or do you have to seed separately?
Introduction Migration and SeedingMigrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.
php artisan migrate:fresh --seed executes the migrate:fresh command, but then it seeds the database. We can use this command when we install the application on a new host, so that it seeds (i.e., inserts data) into the database.
use Undo Seeder for Laravel. When you install UndoSeeder, the following artisan commands are made available: db:seed-undo Undo seeds in the seeds directory. db:seed-refresh Undo seeds run seeds again.
Writing SeedersA seeder class only contains one method by default: run . This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.
You can call migrate:refresh
with the --seed
option to automatically seed after the migrations are complete:
php artisan migrate:refresh --seed
This will rollback and re-run all your migrations and run all seeders afterwards.
Just as a little extra, you can also always use Artisan::call()
to run an artisan command from inside the application:
Artisan::call('db:seed');
or
Artisan::call('db:seed', array('--class' => 'YourSeederClass'));
if you want specific seeder class.
lukasgeiter's answer is correct for test data, but running following artisan command
php artisan migrate:refresh --seed
in production will refresh your database removing any data entered or updated from frontend.
If you want to seed your database along a migration (example rolling out an update to your application keeping existing data), like adding a new table countries along with seed data, you can do the following:
Create a database seeder example YourSeeder.php in database/seeds and your location table migration
class YourTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tablename', function (Blueprint $table) { $table->increments('id'); $table->string('name',1000); $table->timestamps(); $table->softDeletes(); }); $seeder = new YourTableSeeder(); $seeder->run(); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tablename'); } }
Run composer dump-autoload
if there is a php class not found error for YourTableSeeder class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With