thinkjay's avatar

Seeding a Database with the same data after every refresh?

Hi I'm creating an app that has a questionnaire with about 20 questions. Every time I refresh the database, I would like to re-insert the same set of questions. What is the most efficient way you would go about re-importing this data everytime it's refreshed?

0 likes
6 replies
mstnorris's avatar
Level 55

I would use this and tweak it to your needs.

Check out the Faker Documentation for examples of what you can do. Or, just set constants.

ConstantsTableSeeder.php or QuestionsTableSeeder (whatever you like)

<?php

use Carbon\Carbon;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
use Illuminate\Database\QueryException;
use App\Question;
use App\User;

class ConstantsTableSeeder extends Seeder
{
    /**
     *
     */
    public function run()
    {
        $faker = Faker::create('en_US');

        /*
         * Base User Accounts
         */

        // Mike's account
        $michael = User::create([
            'name'       => 'Michael Norris',
            'email'      => 'michael@example.com',
            'password'   => bcrypt('password'),
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        $allUserIds = User::lists('id'); // get a list of all User IDs (in this case just the one)

        // 20 questions
        foreach (range(1, 20) as $questionNumber) {
            $thread = Question::create([
                'user_id'     => $faker->randomElement($allUserIds), // assign a random user
                'title'       => $faker->realText($faker->numberBetween(10,20)), // or a constant as you wish
                'body'        => $faker->realText($faker->numberBetween(10,20)), // as above
                'created_at'  => Carbon::now()->subDays(60)->addDays($faker->numberBetween(1, 60)), // again ...
                'updated_at'  => Carbon::now()->subDays(60)->addDays($faker->numberBetween(1, 60))
            ]);
        }
    }
}

DatabaseSeeder.php the standard included seeder

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder {

    /**
     * @var array
     */
    private $tables = array(
        'questions', // whatever tables you need to "clean"
        'users'
    );

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->cleanDatabase();

        $this->call('ConstantsTableSeeder'); // whatever you called your seeder file above
        $this->call('UsersTableSeeder'); // if you have it
    }

    public function cleanDatabase()
    {

        DB::statement('SET FOREIGN_KEY_CHECKS=0');
        foreach ($this->tables as $table) {
            DB::table($table)->truncate();
        }
        DB::statement('SET FOREIGN_KEY_CHECKS=1');
    }

}

Artisan Commands

You will then need to run

php artisan migrate:refresh --seed // this will reset the database and re-run the migrations and seed the data you specified above

@thinkjay has that answered your question?

2 likes
cipsas's avatar

And then run command: php artisan migrate:refresh --seed --force

mstnorris's avatar

@cipsas would you mind if I include that in my answer as I forgot to mention it. That would make it a more complete answer.

robgeorgeuk's avatar

Great answer from @mstnorris although this will generate different questions each time. If you want the same faker data then you can do this:

$faker->seed(1234);

Or if you want to import your own data then try something like this

$sqlFile = '/database/sql_data/my_question_data.sql';
DB::unprepared(File::get(base_path().$sqlFile));
thinkjay's avatar

thanks! @mstnorris , the code you provided was more helpful than the laravel documentation

1 like

Please or to participate in this conversation.