CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Laravel   How to Insert Dummy Data in Laravel? [Faker Tutorial]

How to Insert Dummy Data in Laravel? [Faker Tutorial]

March 27, 2021 by SNK

In this laravel faker tutorial, we are going to learn how to generate dummy data in laravel using seeders and model factories. These two are the most common ways of generating dummy data into laravel for testing purposes.

We are going to follow step by step tutorial from the start and see how can we create a dummy user in laravel and also the post title, description, and contents. Laravel factory has really made it so easy to work on dummy data using faker.

I assume that you have set your laravel project ready & created a database and migrated the existing user table.

Let’s get started.

What are we going to do?

  1. Create UserSeeder.php and write some code to generate fake data.
  2. Register UserSeeder into databaseSeeder.php.
  3. Creating, registering, and using model factories.
  4. Generating other types of sample data (e.g Blog data: like posts title & contents) to be more familiar.
  5. Conclusion – Seeder VS Model Factories – Which is better?

How to Insert Dummy Data in Laravel?

Option 1: Using Seeders

Open your project and go to the terminal and into the project root. Hit php artisan make:seeder UserSeeder in your terminal.

It will create a seeder file under database/seeders as UserSeeder.php. Register this seeder into the DatabaseSeeder.php inside database/seeder. Import

DatabaseSeeder.php
PHP
1
2
3
4
public function run()
{
  $this->call(UserSeeder::class);
}

Once it is registered head over to UserSeeder.php and write these codes inside it.

UserSeeder.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
public function run(Faker $faker)
{
for ($i = 0; $i < 20; $i++) {
DB::table('users')->insert([
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
                        'password' => bcrypt('password@123'), // Can also be used Hash::make('password@123')
                        'email_verified_at' => now(),
                        'remember_token' => Str::random(10)
               ]);
}
}

Now go to your terminal and hit php artisan db:seed. It will run all your seeder file inside DatabaseSeeder.php.

Another approach would be seeding a particular seed file. You can use specify class like below,

php artisan db:seed --class=UserSeeder. Check your database to see the inserted records

Finally, we have created 20 dummy users in laravel.

Option 2: Using Model Factories

The above option that we have checked is not very practical. Looping over each time and hitting queries is not good for the database when you are moving to production.

This is where model factories come into play. It will generate dummy data into the server without hitting multiple queries. It is very handy when you are developing a new website and need for dummy data right away.

So, let’s get started with the model factories now.  I would like to create model factories that can generate dummy data into users table. Start by creating one.

Go to the terminal in your project root and type php artisan make:factory UserFactory --model=User.

It will create UserFactory.php inside your database/factories. First, register it inside your databaseSeeder.php by copying the code below.

Here 20 is the number of users records that you want to generate at a time. You can choose anything from 1 to 1000. Going more than will hang up your system. So I do not recommend it all at once.

databaseSeeder.php
PHP
1
2
3
4
public function run()
{
Post::factory(20)->create();
}

Now edit your UserFactory.php to generate the dummy data using the code below.

UserFactory.php
PHP
1
2
3
4
5
6
7
8
9
10
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
                'password' => Hash::make('password@123'), // password
                'remember_token' => Str::random(10)
         ];
}

This is the code to generate dummy data for users into the database. Finally, you are all set to generate the data. One last step is to hit php artisan db:seed seed. Now if you check your user’s table you will have 20 records generated inside it.

This is it for the users. Let do another example too. let’s say you are creating a blog and you need dummy articles. So, let’s work on this example. After this example, you will perfectly know how to work with model factories.

Generating sample post data to create a Blog

Generally to create a blog, first, we are going to need some tabes to store our post information like title, description, and content. So let’s create a post table and generate some dummy data into it.

Step – 1

Create posts model and table.

php artisan make:model Post -m

Once the post model and migration is generated. Add fields into your migration. You can use my codes below in order to make it quick.

create_posts_migration
PHP
1
2
3
4
5
6
7
8
9
10
public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title', 255);
            $table->text('description');
            $table->text('content');
            $table->timestamps();
        });
    }

Finally in a terminal hit php artisan migrate:refresh to populate tables into the database. Let’s write some codes to generate dummy data.

Make a model factory first by typing php artisan make:factory PostFactory --model=Post. Register it inside the databaseSeeder.php

databaseSeeder.php
PHP
1
2
3
4
public function run()
{
Post::factory(20)->create();
}

database/factories/PostFactory.php

PostFactory.php
PHP
1
2
3
4
5
6
7
8
public function definition()
{
return [
'title' => $this->faker->sentence(10),
'description' => $this->faker->sentence(50),
'content' => $this->faker->realText(1000)
];
}

Finally hit php artisan db:seed to generate dummy data into the posts table. You can see my table below.

Laravel Model Factories

Laravel Seeders VS Model Factories – Which is better?

Seeders are a great way to generate a small amount of dummy data like 50 or maybe 100. But it does not makes sense to use it when you are using servers as a development machine. Excessive hits to the database may lead to server downtime.

Seeders are good if you are doing development. But you are working directly from your servers then going with model factories is the choice. It works perfectly while generating large amounts of fake data.

This is it on how to insert dummy data in laravel using faker and seeders. We also went through an easy idea on how to use laravel model factories. If you have any problems. You can contact us via the contact form on our website.

 

SHARE ON
Buffer

Enjoyed this article?

Like us on

Laravel create dummy user in laravel how to insert dummy data in laravel laravel factory laravel faker tutorial

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

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

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.