You should go with Seeds: http://laravel.com/docs/5.0/migrations#database-seeding
May 5, 2015
6
Level 1
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?
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
Please or to participate in this conversation.