Laravel 5 Faker Tutorial

Introduction

Database seeding is one of those cool features in Laravel that we all love. However, adding multiple records to the database writing them one by one kind of sucks and takes away a lot of valuable time. This is where faker library comes in.

Faker is a PHP library used to generate fake data for testing purposes. It can be used to generate all sorts of data.

Topics to be covered

We will cover the following topics in this tutorial

  • How to install Faker in Laravel
  • Laravel Faker Basic Usage
  • Laravel Database Seeding using faker

How to install Faker in Laravel

Laravel installs faker by default. You don’t have to manually. You all you to do is start using it.

Faker can be used to generate the following data types

  1. Numbers
  2. Lorem text
  3. Person i.e. titles, names, gender etc.
  4. Addresses
  5. Phone numbers
  6. Companies
  7. Text
  8. DateTime
  9. Internet i.e. domains, URLs, emails etc.
  10. User Agents
  11. Payments i.e. MasterCard
  12. Colour
  13. Files
  14. Images
  15. uuid
  16. Barcodes
  17. Miscellaneous

Read the official faker documentation for more details.

Faker Basic Usage

Let’s start by creating a new Laravel project.

Run the following composer command

composer create-project laravel/Laravel larafaker

Open /app/Http/routes.php

Add the following route

Route::get('/customers',function(){
    $faker = Faker\Factory::create();

    $limit = 10;

    for ($i = 0; $i < $limit; $i++) {
        $faker->name . ', Email Address: ' . $faker->unique()->email . ', Contact No' . $faker->phoneNumber . '<br>';
    }
});

HERE,

  • $faker = Faker\Factory::create(); creates a variable for Faker Factory
  • $limit = 10; sets the for loop limit
  • for ($i = 0; $i < $limit; $i++) {…} executes the same code a number of times as specified by the limit variable
  • echo $faker->name . ', Email Address: ' . $faker->unique()->email . ', Contact No' . $faker->phoneNumber . '<br>'; uses faker to generate a name, unique email address and contact number and display them in the browser.

Load the following URL in your web browser

http://localhost/larafaker/public/customers

You will get results similar to the following

Prof. Luciano Johnson Sr., Email Address: mGibson@hotmail.com, Contact No1-325-254-2558x5828
Issac Turcotte, Email Address: Amy77@Cruickshank.com, Contact No+05(8)9008932202
Alfreda Lesch, Email Address: fWalsh@yahoo.com, Contact No838.460.2999x435
Moses Hilll, Email Address: Mable.Frami@Fritsch.com, Contact No967-214-4263x6676
Mr. Emmett White, Email Address: Kihn.Tess@gmail.com, Contact No+55(7)8197619484
Kristopher Luettgen IV, Email Address: rSkiles@gmail.com, Contact No421-059-9607x2059
Jammie Steuber V, Email Address: Hane.Guiseppe@hotmail.com, Contact No764.271.1083
Narciso Pouros PhD, Email Address: Dare.Jeffery@Reichert.biz, Contact No+06(5)1030483446
Prof. Paul Mills, Email Address: jKertzmann@Mueller.com, Contact No091.167.1263x208
Dr. Lucie Pollich, Email Address: Vivian.White@Nader.com, Contact No03197415831

Now that we have seeing Faker in action, let’s use it in conjunction with seeding.

Laravel Database Seeding using Faker

Let’s start with database configurations. Create a database in MySQL called faker.

Open /.env file in the root directory of the project.

Locate the following lines

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Update the above lines to match your database configurations

DB_HOST=localhost
DB_DATABASE=faker
DB_USERNAME=root
DB_PASSWORD=melody

Save the changes

Let’s now create a database table via migrations that we will populate with data from faker.

php artisan make:migration customers

Open /database/migrations/2015_10_01_130021_customers.php Note: your migration time stamp will be different from the one shown here. It is based on the current time on the server.

Modify the code to the following

<?php

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

class Customers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('contact_number');
            $table->timestamps();
        });
    }

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

If the above code is strange to you, then read the tutorial on Migrations. Use the tutorials index to find the Migrations tutorial.

Run the following artisan command to run the migration

php artisan migrate

You will get the following message

Migrated: 2015_10_01_130021_customers

If you check your database faker, you will be able to see the customers table that was created via migrations.

Run the following artisan command to create a seeder

php artisan make:seeder CustomersTableSeeder

You will get the following message

Seeder created successfully

Open /database/seeds/CustomersTableSeeder.php

Modify the code to the following

<?php

use Illuminate\Database\Seeder;

class CustomersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        $limit = 33;

        for ($i = 0; $i < $limit; $i++) {
            DB::table('customers')->insert([ //,
                'name' => $faker->name,
                'email' => $faker->unique()->email,
                'contact_number' => $faker->phoneNumber,
            ]);
        }
    }
}

HERE,

  • The above code inserts 33 records into customers’ table using data generated by faker.

Run the following artisan command to run the seeder

php artisan db:seed --class=CustomersTableSeeder

If you don’t get any errors, then everything when fine.

Run a SELECT query in MySQL for customers table, you will get results similar to the following.

Laravel Faker Data

Summary

Faker makes it easy to generate tones of dummy data that you can use for testing purposes as you develop your applications. The good thing is it comes already installed in Laravel and using it is as simple as a, b, c and d.

What’s next?

The next tutorial will be on Laravel storage. Storage lets you upload files to the local disk as well as CDN networks such as Amazon S3 etc. If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new Laravel tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2015-10-01

Related Tutorials