Today we are going to teach you on how to generate a huge amount of fake users so you can test your backend.
To generate Fake data in Laravel 5.5, we will use a super library called Faker, you do not need to download it, it is already included in this version of the framework.
https://github.com/fzaninotto/Faker
In Laravel, creating a script of fake data is called "Factory", let's make our first factory!
1 - Open your terminal and create your first factory:
php artisan make:factory Users
This command will generate a file called:
database/factories/UserFactory.php
2 - Open UserFactory.php
And modify this code as needed:
<?php
use Faker\Generator as Faker;
$factory->define(App\User::class, function (Faker $faker) {
static $password;
return [
'name' => $faker->firstNameMale,
'surname' => $faker->lastName,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
'town_id' => $random = rand(1,115),
'activationtoken' => $faker->password,
];
});
You can find a list of variables/functions which are used in the Faker Library here:
https://github.com/fzaninotto/Faker
3 - Let's generate the fake users! Start your terminal and type:
php artisan tinker
Tinker is an interactive language shell
4 - When Tinker is loaded, type this:
factory(App\User::class, 10)->create();
Change the "10" to anything you like, 100, 1000, 10000...whatever.
This command will generate a lot of fake users for you in this format:
App\User {#911
name: "Carmel",
surname: "Donnelly",
email: "kuv******[email protected]",
town_id: 77.0,
activationtoken: "qqG21'ti$b-lSR0=f",
isactivated: 1,
role_id: 1,
updated_at: "2017-10-25 12:02:30",
created_at: "2017-10-25 12:02:30",
id: 112,
},
App\User {#912
name: "Benny",
surname: "Spinka",
email: "cec*****[email protected]",
town_id: 33.0,
activationtoken: "Bp\">P}dk#k?s",
isactivated: 1,
role_id: 1,
updated_at: "2017-10-25 12:02:30",
created_at: "2017-10-25 12:02:30",
id: 113,
},
That's it! Job done.
All your users will be created in a fraction of a second!
Make sure you keep this factory in your script as you may need to recreate more user while testing your Laravel script.