Search code examples
phpdatabaselaravellaravel-4database-migration

Laravel : Migrations & Seeding for production data


My application needs a pre registered data set to work. So i need to insert them in the database when i set up the application.

Laravel propose two mechanisms :

  • Database migrations : "They allow a team to modify the database schema and stay up to date on the current schema state."
  • Database seeding : "Laravel also includes a simple way to seed your database with test data using seed classes."

When I read this description, none of these solutions seems to be adapted.

A similar question has been asked on stackoverflow and answered. The answer proposes to use the a database seeder to populate the database by detecting the current environment :

<?php

class DatabaseSeeder extends Seeder {

    public function run()
    {
            Eloquent::unguard();

            if (App::environment() === 'production')
            {
                $this->call('ProductionSeeder');
            }
            else
            {
                $this->call('StagingSeeder');
            }
    }

}

Of course, this solution works. But i am not sure that it is the right way to do this, because by inserting data using seeders you are losing all the advantages provided by the migration mechanism (database upgrate, rollback...)

I want to know what is the best practice in this case.


Solution

  • Laravel development is about freedom. So, if you need to seed your production database and think DatabaseSeeder is the best place to do so, why not?

    Okay, seeder is mainly to be used with test data, but you'll see some folks using it as you are.

    I see this important kind of seed as part of my migration, since this is something that cannot be out of my database tables and artisan migrate is ran everytime I deploy a new version of my application, so I just do

    php artisan make:migration seed_models_table
    

    And create my seeding stuff in it:

    public function up()
    {
        $models = array(
            array('name' => '...'),
        );
    
        DB::table('models')->insert($models);
    }