How To Insert Fake Data Into Table Using Laravel Factory?

How To Insert Fake Data Into Table Using Laravel Factory

In almost every project that we do, at some point, we need some test data to test our functionality or UI, etc., to test on. To do this, we need to add a lot of fake data to the DB.

With Laravel, this step is super simple. Let’s see how.

In Laravel, we have a factory class that helps us quickly populate fake data.

To start with, you will have to create a Factory class by using the following command:

PHP artisan make:factory UserFactory --model=User

This will create a UserFactory class under Project_folder\Database\Factories.

Open the UserFactory.php file and inside the definition function, add the following code:

return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => 'RandomP@ssword00123',
'remember_token' => Str::random(10),
];

You have now defined the basic parameters of the fake data to be populated.

Next, open the terminal inside the root directory of your project and fire up Tinker by typing the command given below:

php artisan tinker

Now it’s time to actually feed in the fake data.

In order to do that, type the following command while being inside Tinker.

\App\Models\User::factory()->count(25)->create() /// 25 here is the number of records we want to create. Change it as needed.

Once the command has successfully run, you will see an output like this (below).

25 Fake Users created

And if you check your database table, sure enough, you will see 25 new (fake) users have been created there!

That’s how simple it is.

Share This Post

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe To my Future Posts

Get notified whenever I post something new

More To Explore