How to generate fake data in Laravel using factory and faker

laravel faker
Spread the love

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) {

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


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 .

Spread the love

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m an Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website:

View all posts by Anisur Rahman Shahin →

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

Leave a Reply

Your email address will not be published.