Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel 5 - create fake data with $faker & populate database
<?php
/**
* SEEDING DATABASE
*
* Faker Fileds:
* https://github.com/fzaninotto/Faker
*
* 1) Create database, model, migration
* 2) artisan make:seeder
* 3) artisan DB:Seed
*/
use Illuminate\Database\Seeder;
use Faker\Factory;
use App\Todo;
class TodosTableSeed extends Seeder
{
/**
* Run the database seeds.
*
* - use enable model (App\Todo) & factory (Faker\Factory)
*
* - create faker
* - truncate (mysql) - empty the table completely
* - foreach loop / for loop to add data corresponds to fields in database
*/
public function run()
{
$faker = Factory::create();
Todo::truncate();
foreach(range(1,50) as $a) {
Todo::create([
'name' => $faker->name,
'address' => $faker->address,
'phone' => $faker->phoneNumber
]);
}
}
/**
* EXAMPLE 2
*/
public function run()
{
$faker = Factory::create();
Todo::truncate();
for($i=0; $i < 20; $i++) {
Todo::create([
'title' => $faker->text($maxNbChars = 20),
'completed' => $faker->boolean($chanceOfGettingTrue = 50),
'user_id' => $faker->numberBetween($min = 1, $max = 3)
]);
}
}
}
class DatabaseSeeder extends Seeder
{
/**
* Run single table to seed
*/
public function run()
{
$this->call(TodosTableSeed::class);
}
/**
* Run multiple tables at once to seed
*/
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(PostsTableSeeder::class);
$this->call(CommentsTableSeeder::class);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment