Using Faker in Laravel

Introduction

Faker is a PHP library that generates fake data. We can use it extensively while testing our laravel application. We can easily populate our database with fake data. After that, we can run the necessary tests for our requirements.

Setup

Faker package comes along with laravel installation. You can see the composer.json file in your root directory. You can see require-dev something like this,

fzaninotto/faker is the package we are using to generate fake data. If there is no faker package included in composer.json then, you can install it by running following command.

Schema for database table

Now, we will create a simple table using laravel migration. Let’s create a articles table migration like this,

Above command will generate a migration file ‘2018_07_14_031333_create_articles_table.php’ inside database/migrations/ directory. We will add title and body columns to the articles table.

Although ID and Timestamps column (created_at,updated_at) are created by default,We have to add title and body column.

Specific Table Migration In Laravel

In order to create articles table, we have to run the following command.

Hence, we have articles table in the database. Now, we will use faker to populate the articles table in the database

Using Factory

Let’s create a factory where we will add code to insert fake data to our database.

The above command will generate a file ArticleFactory.php inside database/factories/ directory.

In order to make above factory to work, we have to change default Model::class to our article model and return fake title and body. Our code will be,

Here, title will be a text with 50 characters and body will be a text with 200 character. In order to find more details about available options, you can see in following link.

Faker Formatters

Now, Our faker is ready and we need a seeder file to insert fake data.

Create Seeder and Register to Database Seeder

Let’s create articles table seeder with following command.

Above code will generate a seeder class ArticlesTableSeeder.php inside database/seeders/ directory.

Now, we will add some code inside run and register the seeder to main database seeder.

To register the seeder, add following lines of code to DatabaseSeeder.php

So, your Database Seeder should look like following,

Now, In order to run the seeder file, execute following console command.

In this way, we can create a faker for a eloquent model so that we can populate the database using database seeder.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

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