Last active
August 6, 2018 16:44
-
-
Save damir-bubanovic/d67d54b2c19aa233f51f63b3d9f0f4be to your computer and use it in GitHub Desktop.
Laravel 5 - create fake data with $faker & populate database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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