How to create dummy data using factory in Laravel 8

In the process of building application, it is important to test with proper database. You can't manually create dummy database manually and test. You need to use any tool which creates required data.

Laravel ships out of the box solution for that. Laravel provides to create Factory for model and create as many fake data as you want. In this article, we will create Dummy data for Transaction model.

Suppose you have have payment application with lots of transactions data, your Transaction model has few fields which you want to create dummy data. First of all, create Factory for the model using below command.

php artisan make:factory TransactionFactory --model=Transaction

This will create a new factory class at /database/factories folder. Now open the file and add the fields in definition() with the datatype. You can find appropriate format for any field data at Faker documentation.

Now you need to run the factory to create fake database. Make sure your model use Illuminate\Database\Eloquent\Factories\HasFactory trait. You can do this either from laravel tinker command or from the database seeder class.

To run tinker command, first open Terminal and start laravel tinker

php artisan tinker

Now run the command to create dummy data. You can create as many records as you pass number in factory() method.


The second way is to run seeder. Laravel application already have one seeder class at /database/seeders/DatabaseSeeder.php. In the run() method you can add the above line.


namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
     * Seed the application's database.
     * @return void
    public function run()

And from the Terminal run the command to run seeder which will trigger Factory.

php artisan db:seed --class=DatabaseSeeder

This way you can create fake data in Laravel. Please do comment below for new article request.