Hello Artisans,
How are you doing? In this tutorial, I will show you how to generate fake data using factory and faker. Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
I will show you step by step how to use faker in Laravel. Well, let’s start . . . . . . . . . .
First I install a fresh Laravel Project using Composer Command
composer create-project laravel/laravel example-app
Then Go to your Project Folder using this command
cd example-app
Then Open this project in your favorite editor.
Then create a model using this command
php artisan make:model Product -m
This command also create a migration file, You have to go database/migrations folder then open this file 2021_04_16_111326_create_products_table.php . Then paste this code in up() method
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name',30)->unique();
$table->float('price',5);
$table->text('description');
$table->boolean('status')->default(false);
$table->timestamps();
});
Note : You can add column according to your requirement.
Then run . . . .
php artisan migrate
Your table has been created successfully.
Now Create a factory class using this command . . . . .
php artisan make:factory ProductFactory --model=Product
Now go to database/factories folder open ProductFactory.php file . Then you can see the definition() method return an array . Copy this code and merge it with the definition method.
public function definition()
{
return [
'name' => $this->faker->name,
'price' => rand(100,200),
'description' => $this->faker->text,
'status' => 1,
];
}
Note : Your definition method should be like top code if you use above schema
Then go to database/seeders folder and open DatabaseSeeder.php file paste this code
\App\Models\Product::factory(10)->create();
In this factory method’s parameter (10) you can define a number that how many amount of number of products do you want.
Then run this code
php artisan db:seed
Then see your Product table in database inserted fake 10 data .

One Comment on “How to generate fake data in Laravel using factory and faker”