Generate Fake Data Using Laravel Faker

ganarete-fake-data-using-laravel-faker

In this tutorial, I will show you how to generate fake data using laravel faker. For that we will use this Faker package. 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.

Best thing about laravel is, it comes with this Faker package by default in development mode. You can check it here.

laravel-faker

Now, lets understand about how we can use faker to generate fake data step by step using example.

Let’s install fresh laravel project using composer using below command.

composer create-project --prefer-dist laravel/laravel lara-faker-tutorial

Above command will create fresh laravel project.

Setting up database in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lara-faker-example
DB_USERNAME=root
DB_PASSWORD=

Now run artisan migration command.

php artisan migrate

Above artisan migrate command will create database tables using migrations.

Next lets create todo migration file using below command.

php artisan make:migration create_todos_table

Above command will generate todos migration file under database/migrations directory. Open todos migration file and add fields shown as below.

2019_08_18_020057_create_todos_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTodosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('todos', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('description');
            $table->integer('priority')->comment('1=Low, 2=Medium, 3=High');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('todos');
    }
}

Next, we will create todo model file using artisan model command.

php artisan make:model Todo

Above command will create model file Todo.php under app/ directory. Open Todo.php file and update as shown below.

Todo.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'description', 'priority',
    ];
}

Here we are not going to do any activity like add, edit, listing or delete todo. So we won’t make TodoController.php file.

Now, lets create TodoFactory.php file under database/factories/ directory.

TodoFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Todo;
use Illuminate\Support\Str;
use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(Todo::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence($nbWords = 6, $variableNbWords = true),  // Random task title
        'description' => $faker->text(), // Random task description
        'priority' => rand(1,3), // Task Priority Low, Medium, High
    ];
});

Generate Fake Data Using Tinker

We have TodoFactory.php file ready as shown above. Now, Open command line tool and run below command.

php artisan tinker

Next run below command to generate 50 rows of random todos.

>>> factory(App\Todo::class,50)->create();

Generate Fake Data Using Seeder

This is another method to insert fake data in database using seeder. Lets see step by step. We will use above todos example for this. We will use same TodoFactory.php here too.

Lets create seeder for Todo using below artisan command.

php artisan make:seeder TodoTableSeeder

Above command will generate TodoTableSeeder.php file in database/seeds directory. Open TodoTableSeeder.php and update code shown as below.

TodoTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class TodoTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Todo::class, 50)->create();
    }
}

Next we need to declare TodoTableSeeder inside DatabaseSeeder seeder which is also located under same directory.

DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(TodoTableSeeder::class);
    }
}

We can add multiple seeder file to run all seeder at once. This is very helpful while fill-up data with some pre-defined data.

Now we will run below artisan command to insert 50 fake rows in todos database table.

php artisan db:seed

Its done, You have successfully added 50 rows in todos database table.

Various Faker Formatters

Faker not only generate first name, last name but its also generate wide range of data shown as below.

// Base
$faker->randomDigit             // 7
$faker->randomDigitNotNull      // 5
$faker->randomNumber($nbDigits = NULL, $strict = false) // 79907610
$faker->randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
$faker->numberBetween($min = 1000, $max = 9000) // 8567
$faker->randomLetter            // 'b'


// returns randomly ordered subsequence of a provided array
$faker->randomElements($array = array ('a','b','c'), $count = 1) // array('c')
$faker->randomElement($array = array ('a','b','c')) // 'b'
$faker->shuffle('hello, world') // 'rlo,h eoldlw'
$faker->shuffle(array(1, 2, 3)) // array(2, 1, 3)
$faker->numerify('Hello ###') // 'Hello 609'
$faker->lexify('Hello ???') // 'Hello wgt'
$faker->bothify('Hello ##??') // 'Hello 42jz'
$faker->asciify('Hello ***') // 'Hello R6+'
$faker->regexify('[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}'); // [email protected]

// Person
$faker->title($gender = null|'male'|'female')     // 'Ms.'
$faker->titleMale                                 // 'Mr.'
$faker->titleFemale                               // 'Ms.'
$faker->suffix                                    // 'Jr.'
$faker->name($gender = null|'male'|'female')      // 'Dr. Zane Stroman'
$faker->firstName($gender = null|'male'|'female') // 'Maynard'
$faker->firstNameMale                             // 'Maynard'
$faker->firstNameFemale                           // 'Rachel'
$faker->lastName                                  // 'Zulauf'

// Address
$faker->cityPrefix                          // 'Lake'
$faker->secondaryAddress                    // 'Suite 961'
$faker->state                               // 'NewMexico'
$faker->stateAbbr                           // 'OH'
$faker->citySuffix                          // 'borough'
$faker->streetSuffix                        // 'Keys'
$faker->buildingNumber                      // '484'
$faker->city                                // 'West Judge'
$faker->streetName                          // 'Keegan Trail'
$faker->streetAddress                       // '439 Karley Loaf Suite 897'
$faker->postcode                            // '17916'
$faker->address                             // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473'
$faker->country                             // 'Falkland Islands (Malvinas)'
$faker->latitude($min = -90, $max = 90)     // 77.147489
$faker->longitude($min = -180, $max = 180)  // 86.211205

// Phone Number
$faker->phoneNumber             // '201-886-0269 x3767'
$faker->tollFreePhoneNumber     // '(888) 937-7238'
$faker->e164PhoneNumber     // '+27113456789'

There are so many faker formatters available. You can check More faker formatters .

Faker Localization [Language]

Faker\Factory can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallback to the default locale (en_US).

<?php
$faker = Faker\Factory::create('fr_FR'); // create a French faker
for ($i = 0; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Luce du Coulon
  // Auguste Dupont
  // Roger Le Voisin
  // Alexandre Lacroix
  // Jacques Humbert-Roy
  // Thérèse Guillet-Andre
  // Gilles Gros-Bodin
  // Amélie Pires
  // Marcel Laporte
  // Geneviève Marchal

In above example, We have generated French name using French localization. Here is a list of various faker locale.

Final Words…

I hope that you may like this tutorial on generation fake data in laravel using Faker. Let me know if you have any issue regarding faker. Also share this tutorial with your friends. Thank you  🙂

About Chintan Panchal

I am web developer having 4+ year of experience of web development. I have worked on codeigniter, symfony, laravel and wordpress.

View all posts by Chintan Panchal →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.