Learning Management Platform for Written Tutorial Series.

Laravel 6 Faker Tutorial

Laravel 6 Faker Tutorial

Data is the life line of most web applications. When you are working on a shopping cart, you will need sample products so that you can see how they will be displayed on the user interface. You need data to see how the system will perform when it has over 100,000 records in the database. But how and where do you get these dummy records from?

This is where faker comes in. It is a library that allows us to generate fake data that can be populated into the database during development for testing purposes. In this lesson, you will learn how to use faker in a Laravel application.

Topics to be covered

We will cover the following topics in this lesson

  • Introduction to faker
  • Faker basics
  • Model factories and faker
  • Laravel database seeding using faker

Introduction to faker

Faker is a library that generates fake data for a variety of data types. Faker is shipped with Laravel by default so you don't have to install it as a third-party package.

Faker can be used to generate the following data types

  • Numbers
  • Lorem text
  • Person i.e. titles, names, gender etc.
  • Addresses
  • Phone numbers
  • Companies
  • Text
  • DateTime
  • Internet i.e. domains, URLs, emails etc.
  • User Agents
  • Payments i.e. MasterCard
  • Colour
  • Files
  • Images
  • uuid
  • Barcodes
  • Miscellaneous

Read the official faker documentation for more details.

Faker basics

Let's start by creating a new Laravel project.

Run the following composer command

composer create-project laravel/Laravel larafaker 6.0.*

HERE,

  • The above command creates a new project using the latest version of Laravel 6.0

Let's now add a web route that we will use to test generating fake data like so

Open /routes.web.php

Add the following route definition

Route::get('/customers',function(){
    $faker = Faker\Factory::create();
    
    $limit = 10;
    echo '<ul>';
    for ($i = 0; $i < $limit; $i++) {
        $customer = $faker->name . ' - ' . $faker->unique()->email . ' - ' . $faker->phoneNumber;
        echo "<li> $customer</li>";
    }
    echo '</ul>';
});

HERE,

  • $faker = Faker\Factory::create(); creates an instance of Faker Factory object.
  • $limit = 10; defines the total number of records that we want to generate.
  • for ($i = 0; $i < $limit; $i++) {...} uses a for loop to iterate 10 creating fake customer records. $faker->name returns a random name, $faker->unique()->email returns a fake unique email address and $faker->phoneNumber returns a fake phone number. We HTML tags are used to display an unordered list.

Run the following command to start the built-in server

php artisan serve

You can now load the following URL into your browser

http://localhost:8000/customers

You should be able to get the following results

Laravel 6 Faker

Model factories and faker

Model factories allow us to quickly generate a records for a model. Let us create a model that will persist the data that we generated in the above example to the database.

Run the following command to create a model and its associated database migration file.

php artisan make:model Customer -m

HERE,

  • php artisan make:model Customer -m the option -m is used to generate a migration file at the time of creating the model class.

Open the model Customer in the directory /app and modify the code as follows

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $fillable = [
        'name',
        'email',
        'phone_number'
    ];
}

HERE,

  • protected $fillable = [...] whitelists the database fields that we want to be able to manipulate using our model class.

Next open the database migration file in /database/migrations. The file name has a timestamp and create_customers_table.php

Update the code as follows

<?php

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

class CreateCustomersTable extends Migration
{
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('phone_number');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

If you are not familiar with the concept of database migrations in Laravel then read our tutorial on database migrations.

Before we run our database migration file, we first need to set the database connection parameters

Run the following command to create a database in MySQL

CREATE DATABASE larafaker;

Next open the configuration file .env and update the database connection parameters like so

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=larafaker
DB_USERNAME=root
DB_PASSWORD=your_password

Run the following artisan command to migrate the database definition

php artisan migrate

HERE,

  • The above command creates tables in our new database including the customers table.

Let's now create a factory for our Customer model like so

php artisan make:factory CustomerFactory --model=Customer

Open the factory CustomerFactory in the directory /database/factories

Modify the code as follows

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Customer;
use Faker\Generator as Faker;

$factory->define(Customer::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'phone_number' => $faker->phoneNumber,
    ];
});

HERE,

  • use App\Customer; imports the customer model
  • use Faker\Generator as Faker; brings in the class Generator into the factory scope under the alias Faker
  • $factory->define(Customer::class, function (Faker $faker) {...} defines a class factory for the model Customer then uses faker to assigns values to the model attributes name, email, and phone_number

We will now use tinker to create 10 customer records in the database like so

Run the following command to invoke tinker

php artisan tinker

When tinker has opened, execute the following command

factory(App\Customer::class, 10)->create();

HERE,

  • factory(App\Customer::class, 10)->create(); creates 10 records as specified in the argument to the factory method. The records are created using the CustomerFactory that we created.

Run the following command in MySQL against the larafaker database

SELECT * FROM customers;

You should be able to see results similar to the following

Laravel Faker Model Factory

Laravel database seeding using faker

We have another option of creating database records using a technical called database seeding. This technical allows us to create a database seeder file that basically runs the command that we executed directory in tinker.

Run the following command to create a customers seeder

php artisan make:seeder CustomersTableSeeder

HERE,

  • The above command generates boiler-plate code for a database seeder

Open the seeder file that has been created in the directory /database/seed directory

Update the code as follows

<?php

use Illuminate\Database\Seeder;

class CustomersTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Customer::class, 30)->create();
    }
}

HERE,

  • public function run(){} the run method is executed when we run the database seed command. factory(App\Customer::class, 30)->create(); creates 30 dummy customer records using the CustomerFactory that we created.

We can now execute our database seeder using artisan like so

php artisan db:seed --class=CustomersTableSeeder

HERE,

  • The above command seeds the seeder called CustomersTableSeeder

If you check the database after executing the above command, you should be able to see the newly created database records.

Summary

Faker is a powerful easy to use library that allows developers to quickly create thousands of dummy records for the database during development. Faker is usually used together with model factories. Database seeding refers to the process of generating dummy records for the database. We can seed the database using tinker or by creating and executing a database file.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...