Generate Test or Dummy Data with Laravel 8 Factory Tinker

Last updated on by Digamber

In this Laravel 8 factory tutorial, you will learn how to generate and insert test or fake or dummy data into the database using Laravel 8 factory. Not just that you will also learn how to use PHP Faker library in Laravel app to generate fake data.

Faker is an exorbitantly powerful PHP library that generates fake data for you and gives you moksha from all the pain you feel while developing a new application.

Developing an application requires lots of data to test the robustness of specific functionality be it user records, pagination, articles; If you manually add hundreds of records for testing, then it may take more time.

Fret not, and we have a painless solution for you to create test data in laravel:

Laravel offers factory tinker, and you can count on Laravel Tinker with your eyes closed, it lets you create fake records or dummy data in the database. With the help of Laravel factory tinker, you can generate thousands of records and add into the database within seconds.

You can seed the database with just a simple Model class, so without further ado, let’s see how easy it is to create fake or test records using laravel factory.

You can find the documentation for Tinker on the Laravel website.

Install Laravel Project

You need to lay down the composer tool in your development system to install the laravel project, afterwards use the following command to manifest a new laravel app:

composer create-project laravel/laravel laravel-factory-tinker-example --prefer-dist

Make Database Connection

If you are developing a laravel app and wants to connect to the database, so open the .env file then insert your database name, username likewise the password:

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

Generate Model & Run Migration

For the database seeding example, let’s create a Blog model usually it will create a table in the database with table columns as properties.

php artisan make:model Blog -m

Add table properties in app/Models/Blog.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 
        'url', 
        'category',
        'description'
    ];    
}

Place table properties in database/migrations/create_blogs_table.php migration file as well:

<?php

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

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('url');
            $table->string('category');
            $table->string('description');                        
            $table->timestamps();
        });
    }

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

Next, you can migrate table properties in the database with the artisan migrate command:

php artisan migrate

Create Custom Factory

To work with laravel factory, you need to create a custom factory class in Laravel:

php artisan make:factory BlogFactory --model=Blog

Go ahead and place the below code in database\factories\BlogFactory.php file:

<?php

namespace Database\Factories;

use App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class BlogFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Blog::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'url' => Str::slug($this->faker->name),
            'category' => $this->faker->name,
            'description' => $this->faker->text,
        ];
    }
}

Generate Dummy Records with Factory Tinker

Eventually, we are about to create 1000 test data and seed them into the Blog table. Use the below command to check your database later for fake data similarly.

php artisan tinker

You’ve entered into the Psy Shell now execute the command:

Blog::factory()->count(1000)->create()

Next, see the generated Blog records inside PHPMyAdmin.

Remember, we are generating the data for Blog model so we used Blog::factory(), likewise append the same “Modal name” for which you are generating the dummy data. For instance we can do the following for User model:

User::factory()->count(500)->create()

In this tutorial, we created the limited properties, however, you can generate more properties with Faker:

  • Lorem Ipsum Text
  • Person
  • Address
  • Phone Number
  • Company
  • Real Text
  • Date and Time
  • Internet
  • User Agent
  • Payment
  • Color
  • File
  • Image
  • Uuid
  • Barcode
  • Miscellaneous
  • Biased
  • Html Lorem

Summary

The Laravel 8 Factory Tinker tutorial is over. This Factory Tinker example explained how to generate fake or test data using custom Factory tinker in Laravel application for two different Model or database table. Nonetheless, I believe this tutorial will help you in your development journey. Share your feedback about this tutorial and help others.

Thank you, have a nice day!