Laravel Faker Generate Dummy Data With Model Factory Tinker

laravel passport, laravel faker, laravel elasticsearch, install laravel on windows, laravel scout search, laravel pagination search

Today, we will learn on laravel faker for generating dummy data in MySQL database.

Sometimes, we need to generate fake data into database for some testing purpose.

In laravel, there is a model factory called Tinker which allows us to do this using the faker.

You can use the following video to see how the final outcome of this example look :

What is Laravel Faker ?

Faker is the library which helps us to generate fake data in our laravel application.

It is a library which allows you to manage fake data for testing purpose. It can support various types of data like name, country, phone number etc.

It is easy to use and integrate in the laravel project using the Factory feature of the laravel framework.

Now follow all the below steps to make fake data using faker and tinker factory.

Move 1. New Project and Database

Open up your terminal or command prompt and hit the following command

composer create-project laravel/laravel=7 laraDummy --prefer-dist

Above line will create one laravel project with the name as “laraDummy”

Now let us connect our laravel project with the MySQL Database.

I am using sequel pro as the database maintenance tool. You can use other platform such as phpMyAdmin and others also.

In your database management tool, make a new database and give it a name as “laraDummy”

Now open your laravel project in the editor platform such as “Visual studio code” , “sublime text” etc.

Now go to your .env file from the editor tool. Inside .env file, find the following lines

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraDummy
DB_USERNAME=root
DB_PASSWORD=

In the above lines, fill the details as per the settings of your machine or computer.

I have written the database and username. I do not have any password. You should also check the host at which your local host is running.

Move 2. Playing With User Table

Laravel gives us default table called “User” with all controller, migration and Model files.

So let us first fill the data in Users table.

Go to the command prompt and fire the following one

php artisan migrate

Above line will create the Users table into the database. Check once in your database. This table should be empty at this moment.

Now write the below command

php artisan tinker

This command will create virtual environment in your terminal or command prompt.

Now hit the following command

factory(App\User::class, 50)->create();

Above line will create 50 virtual rows into the Users table. You should be able to see the details of these 50 rows in your cmd only.

Below are the lines I can see in my command prompt

=> Illuminate\Database\Eloquent\Collection {#3033
     all: [
       App\User {#3036
         name: "Mrs. Janet Kshlerin III",
         email: "wsauer@example.org",
         email_verified_at: "2020-04-05 11:55:57",
         updated_at: "2020-04-05 11:55:57",
         created_at: "2020-04-05 11:55:57",
         id: 51,
       },
       App\User {#3038
         name: "Reilly Borer",
         email: "rossie.connelly@example.org",
         email_verified_at: "2020-04-05 11:55:57",
         updated_at: "2020-04-05 11:55:57",
         created_at: "2020-04-05 11:55:57",
         id: 52,
       },
       App\User {#3183
         name: "Prof. Dell Graham",
         email: "sim58@example.com",
         email_verified_at: "2020-04-05 11:55:57",
         updated_at: "2020-04-05 11:55:57",
         created_at: "2020-04-05 11:55:57",
         id: 53,
       },
       App\User {#3185
         name: "Bennie Hartmann",
         email: "edgar08@example.com",
         email_verified_at: "2020-04-05 11:55:57",
         updated_at: "2020-04-05 11:55:57",
         created_at: "2020-04-05 11:55:57",
         id: 54,
       },
       App\User {#3195
         name: "Jules Heathcote",
         email: "jacobson.ellen@example.net",
         email_verified_at: "2020-04-05 11:55:57",
         updated_at: "2020-04-05 11:55:57",
         created_at: "2020-04-05 11:55:57",
         id: 55,
       },
     .......
..............till 50th row data

Now see your database, there must be 50 new records in the Users table.

Move 3. Adding Data In Other Table

Users table in pre written so it is easy to use tinker and factory on this table.

But if you want to add fake data in any other table then it is little long process.

First of all, run the following command to create the migration file.

php artisan make:migration create_workers_table

Above files will help us to make migration file for Workers table.

After this command, navigate to the app->database->migrations folder. Inside migrations folder, you will find a new file which may have name like timestamp_create_workers_table.php file.

Inside this imestamp_create_workers_table.php file, add the below code snippet

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWorkersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('workers', function (Blueprint $table) {
            $table->bigIncrements('id'); 
            $table->string('name'); 
            $table->text('country');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('workers');
    }
}

In the above code, up() function defines the column names for the Workers table.

This table have name, country and time stamp as the column.

After this, go to your command prompt and run the following

php artisan migrate

This command will create the Workers table into the database. This table should be empty right now.

Now let us create Worker Model class. For this, fire the below command

php artisan make:model Worker

Now go to the app->Worker.php file. This file is developed by the above command.

Write down the following coding lines inside app->Worker.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Worker extends Model
{
    //
    public $table = "workers"; 
}

Look at the only line present in the above file. This line is assigning this model file to the workers table.

Now navigate to the app->database->factories->UserFactory.php file.

Source code for the UserFactory.php file should look like the below

<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use App\Worker;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});
$factory->define(Worker::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'country' => $faker->country,
       
    ];
});

Make sure that in the above file you have added the below line

use App\Worker;

And also, you need to write the factory lines for the workers table as the below

$factory->define(Worker::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'country' => $faker->country,
       
    ];
});

Above lines are using the Faker library to generate fake name and fake country.

Our work on code editor is now complete. Now go to your command prompt and hit the following command

php artisan tinker

After running the above tinker command, write the below line in command prompt

factory(App\Worker::class, 50)->create();

After firing the above command, check your database, there must be 50 new records or rows in the workers table.

Download Code

Click to download full source code