Seeders make it easy to create fake test data. Exactly, what can be done with the seeders is to generate fake data and save it in the database, with this we will not have to go inserting one by one the test data in the database.
First we have to create the file for the seeder, we will do it with an artisan command:
1 |
php artisan make:seeder UsersTableSeeder |
And put this code in the run() function:
1 2 3 4 5 6 7 8 9 10 |
//top of the file use App\User; use App\Post; ... //create 5 user and 30 posts for each user factory(User::class, 5)->create()->each(function($u) { factory(Post::class, 30)->create(['user_id'=>$u->id]); }); |
This code what it does is generating 5 users and assigning to each user 30 posts.
And add this line in DatabaseSeeder.php in the run() function, to run when we run the seeders:
1 |
$this->call(UsersTableSeeder::class); |
To indicate what type of data is to be inserted in the database, we have to put it in the file database/factories/ModelFactory.php :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// user data types $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('123456'), 'remember_token' => str_random(10), 'country' => $faker->word, ]; }); // posts data types $factory->define(App\Post::class, function (Faker\Generator $faker) { return [ 'title' => $faker->sentence(8), 'body' => $faker->paragraph(2), 'user_id' => function() { return factory(App\User::class)->create()->id; }, ]; }); |
The code is quite descriptive. If you want to see all the types of data that are admitted you can see them here.
To run the seeders, we will have to do it through the command line:
1 |
php artisan db:seed |
If everything is OK, we would already have the information in our database and that’s how we can save a lot of time when creating test data.
-
– Seeders: https://laravel.com/docs/5.4/seeding