How to Add Fake Records For Testing Using Factory in Laravel?

On our websites sometimes we need to add fake records to test. They must look like real records and we must be able to add them with ease. Laravel enables us to do so. For example, we want to add few Leads in our database for testing. Let’s start this.

First we will make our Lead model with migration.

php artisan make:model Lead -m

Now we will place this code in our migration.

<?php

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

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

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

And we need to run this command to migrate. This will create leads table in database.

php artisan migrate

Now we will add following code in our Lead model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Now we will create new Factory by running this command.

php artisan make:Factory LeadFactory

And then we will add this code in our LeadFactory.

<?php

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

use App\Lead;
use Faker\Generator as Faker;

$factory->define( Lead::class, function ( Faker $faker ) {
	return [
		'name'       => $faker->name,
		'email'      => $faker->email,
		'created_at' => now(),
		'updated_at' => now(),
	];
} );

Then we will create a seeder by running this command.

php artisan make:seeder LeadsSeeder

And we will place this code in LeadsSeeder

<?php

use Illuminate\Database\Seeder;

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

Now we will run our seeder by using this command and it will add 10 leads in our database. We can add ten leads every time we run this command.

php artisan db:seed --class=LeadsSeeder

I hope now you can easily add few records in Database for testing purpose. If you have any problems please leave a command. We appreciate that.