Seeding fake data with a factory & testing via API in Laravel / Lumen.

Rabib Galib
2 min readJun 27, 2020

--

Here, we’ll learn how to generate fake data with factory & seed into database. After installation of laravel & composer successfully, first set up Database configuration in .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=firstAuthApp
DB_USERNAME=root
DB_PASSWORD=

Please run the below command in terminal.

php artisan make:model Person -mf

This command will create a migration file in database/migrations & a factory file in database/factories

Now update the people_table with below code in database/migrations

Schema::create('people', function (Blueprint $table) {	
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('phone');
$table->string('city');
$table->timestamps();
});

Update the PersonFactory.php with below code in database/factories

$factory->define(Person::class, function (Faker $faker) {
return [
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->safeEmail,
'phone' => $faker->phoneNumber,
'city' => $faker->city,
];
});

Now create a seeder by below command. This will create a seeder in database/seeds

php artisan make:seed PersonTableSeeder

Now update PersonTableSeeder file with below code

public function run()
{
factory(Person::class, 30)->create();
}

Update the DatabaseSeeder file too with below code

public function run()
{
// $this->call(UserSeeder::class);
$this->call(PersonTableSeeder::class);
}

Now please do following commands in terminal

php artisan migrate

php artisan db:seed
composer dump-autoloadphp artisan serve

To test, please add below code in routes/api.php

use App\Person;
Route::get('/person/{person}', function(Person $person) {
return $person;
});

You can also check the database in your localhost.

Have fun 🔥 💪

If you have any query, please put in below. Find me on Github.

--

--

Rabib Galib
Rabib Galib

Written by Rabib Galib

Senior Software Engineer, Masters in Computer Science & Engineering, PHP, Python, Chatbot Expert, AI Research

No responses yet