Laravel seed after migrating

34,830

Solution 1

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.

Solution 2

If you don't want to delete existing data and want to seed after migrating

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.

Solution 3

While lukasgeiter's answer is correct, I'd like to elaborate on your second question.

Or do you have to seed separately?

Yes. Since you're talking about test data you should avoid coupling seeding with migration. Of course if this were not test data, but application data, you could always make inserting data part of the migration.

As an aside, if you want to seed your data as part of testing, you can call $this->seed() from within your Laravel test case.

Share:
34,830
imperium2335
Author by

imperium2335

PHP, JS, MySQL coder and retired 3D modeler.

Updated on June 04, 2020

Comments

  • imperium2335
    imperium2335 almost 4 years

    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?