Generate Fake Data in Laravel 7 using Faker

By CodersDrive
14-Jun-2020
Laravel

As a developer in many situations we require fake data for testing purpose. In laravel we can generate "Fake Data" using built in "Faker" utility.

Laravel has built in package fzaninotto/faker to perform this function of seeding Fake Date for testing purpose. It will be installed when you create your new Laravel project.

If for some reason it is not installed you can get it by running the following command at command prompt from your project location.

composer require fzaninotto/faker --dev
Example: Create Clients Fake Data
Step-1 Create a Model and Migration

First create a Model Client and its migration using the following command.

php artisan make:model Client -m

This command will generate Client.php Model Class at app/ path and its migration file 2020_mm_dd_xxxxxx_create_clients_table.php at database/migrations/ path. This migration file has the table column names, you can edit this file and add our required columns as shown below.

<?php

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

class CreateClientsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->id();
            $table->string('firstName');
            $table->string('lastName');
            $table->string('email');
            $table->string('phoneNumber');
            $table->string('address');
            $table->string('city');
            $table->string('country');
            $table->timestamps();
        });
    }

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

In this example we have added 7 fields to this migration file ('firstName', 'lastName', 'email', 'phoneNumber', 'address', 'city', 'country'). Now run the following command to create "clients" table in your MySQL DB.

php artisan migrate

Now you can verify the created clients table logging into your MySQL DB.

Step-2 Make Model fields fillable

As Laravel works on MVC (Model View Controller) type architecture, for security reasons when ever a Model is created by default all the fields are not allowed to add data through Controllers. To enable this we have to edit the created Model Client at app/ location and edit the code as shown below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $guarded = [];
}

In the code shown protected $guarded = []; means no Model fields are guarded, hence all the table coulmns can be updated through Controllers. If we want to protect some columns not to be allowed for add/update through Controllers you can add them under "$guarded" array like this protected $guarded = ['address'];.

There is also otherway to protect using protected $fillable = ['firstName','lastName'];. Which means only 'firstName', 'lastName' fields are allowed to add/update through Controller.

Step-3 Create ModelFactory

In this step we will create a ModelFactory for Clients as ClientFactory using the following command.

php artisan make:factory ClientFactory

This will create a file ClientFactory.php at database/factories/. Edit this file and add the following code to it.

<?php

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

use App\Client;
use Faker\Generator as Faker;

$factory->define(Client::class, function (Faker $faker) {
    return [
        'firstName' => $faker->firstName,
        'lastName' => $faker->lastName,
        'email' => $faker->email,
        'phoneNumber' => $faker->phoneNumber,
        'address' => $faker->address,
        'city' => $faker->city,
        'country' => $faker->country,
        
    ];
});

Here every Model field is mapped to the corresponding Factory field types to match to our required content type. For example 'email' => $faker->email, indicates that this field should be filled with dummy data of emails only. To know different types of supported Factory data formats click here.

Step-4 Create TableSeeder

Now create a clients table seeder ClientsTableSeeder.php using the following command.

php artisan make:seeder ClientsTableSeeder

Edit the file ClientsTableSeeder.php created at database/seeds/ and add the following code to it. This is created to create 100 dummy client records whenever it is called.

<?php

use Illuminate\Database\Seeder;
use App\Client;

class ClientsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return  void
     */
    public function run()
    {
        $count = 100;
        factory(Client::class, $count)->create();
    }
}
Step-5 Add TableSeeder to DatabaseSeeder

Now add this created ClientsTableSeeder to DatabaseSeeder.php available at database/seeds/ as shown below.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return  void
     */
    public function run()
    {
        // $this->call(UserSeeder::class);
        $this->call(ClientsTableSeeder::class);
    }
}
Step-6 Run DB:Seed Command

Finally we are ready to pump our clients table with dummy data of 100 records. For this to happen run the following command.

php artisan db:seed

Once the successful message is displayed, you can check the same by logging into your MySQL DB.

fake data generator

Hope you too got this at your end. Thank you for reading this post. Happy coding.


Laravel MySQL Php

Search blog..!

Connect with us