Using faker in Laravel 9 to generate test / dummy data

It’s obviously cumbersome to enter all the data in the tables in your app for testing purposes. That’s where factories and faker come handy in generating tons of data on the fly. So, in this tutorial we’ll use factory and faker in Laravel 9 in order to generate fake / dummy data for testing purposes.

Laravel 9.x requires a minimum PHP version of 8.0. This tutorial assumes that you are using Linux, MacOS or WSL on Windows and Node.js, Composer and PHP 8 along with required modules i.e bcmatch, sqlite, mbstring, xml, zip, gd, mcrypt are properly installed. Also make sure that SQLite is installed as we’ll be using SQLite to keep things simple and quick; you may use MySQL or PostgreSQL as you like, however make sure the corresponding PHP module is installed too.

Using Composer, enter following command in terminal to install Laravel 9;

composer create-project laravel/laravel app 9.*

Now go inside newly created app directory by executing;

cd app

Then, setup database and Laravel environment file. Here, I’m configuring SQLite database for simplicity purposes.

Being in parent directory (app), execute following command in order to create new SQLite database file;

touch database/database.sqlite

Then find .env config file in the parent directory, open it and amend DB_CONNECTION line as follows;

DB_CONNECTION = sqlite

You can remove DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD from .env when using SQLite database.

Now, enter the following command to create Employee model along with the migration:

php artisan make:model Employee -m

Open newly created migration file from database/migrations/ which is named something like …create_employees_table.php and then insert the desired table fields;

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->text('address');
            $table->integer('age');
            $table->integer('salary');
            $table->enum("department", ["Finance", "Admin", "Marketing", "Production"]);
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('employees');
    }
};

Enter following command in parent directory to migrate the above migration;

php artisan migrate

Now, create factory for generating test data by executing following command;

php artisan make:factory EmployeeFactory

Then, insert following code into database/factories/EmployeeFactory.php file;

<?php
namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class EmployeeFactory extends Factory
{
    public function definition()
    {
        return [
			"name" => $this->faker->name(),
			"email" => $this->faker->unique()->safeEmail,
			"address" => $this->faker->address,
			"age" => $this->faker->numberBetween(25, 65),
			"salary" => $this->faker->numberBetween(25000, 100000),
			"department" => $this->faker->randomElement([
				"Finance", "Admin", "Marketing", "Production"
			]),
        ];
    }
}

Now, our factory is ready to generate dummy data using the power of faker. In order to populate database table quickly, let’s enter following command to invoke tinker;

php artisan tinker

And then enter following command to create 50 employees;

Employee::factory(50)->create()

That’s it! 50 employees with dummy data have been generated and inserted into employees database table. Type ‘exit’ and press Enter in order to exit tinker.

Now, in order to check employees data, open routes/web.php and change it as follows;

<?php
use Illuminate\Support\Facades\Route;
use App\Models\Employee;

Route::get('/', function () {
	$employees = Employee::all();
	dd($employees);
	return view('welcome');
});

dd() function is a handy tool which interrupts the execution of script and dumps the output of the given variable. That’s very useful in debugging the app, so make plenty use of it.

Finally, execute following command in parent directory to run PHP development server;

php artisan serv

Open browser and enter following URL in address bar;

http://localhost:8000

Calling the above URL will trigger the default ‘/’ route which in return will execute the callback function that fetches all records from employees table. Then dd() function dumps the data inside $employees object onto the browser and then immediately ends the execution of script, that’s why ‘welcome’ view is not rendered. On the browser you get the $employees variable’s data displayed in a well organized manner in order to facilitate traversing what’s inside. So, just spend a bit of time here and explore what’s actually inside a Laravel’s Collection object.

1 thought on “Using faker in Laravel 9 to generate test / dummy data”

Leave a Comment