Seeder with Faker Library Concept in Laravel 8

Reading Time: 8 minutes
26,577 Views

For application testing we always need data. In case if our application is running live then we can create test data via web portal or from some where else. But at initial point i.e at development phase we need data in bulk amount.

In laravel we have the default system to generate fake data named as Laravel Seeder. So, inside this article we will see the concept of Seeder and Factory. By the help of these concepts we will see to generate Fake or test data in laravel 8.

Learn More –

Let’s get started – Seeder with Faker Library Concept in Laravel 8.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

To learn Routing in Laravel 8 click here.


Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

Successfully, we have created a database.

To connect, Open up .env file which will be at root of project.

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

Successfully, we have connected database to application.


Create Migrations To Generate Table

To create migration files for tables we need to run few simple php artisan commands. Let’s say we need to table called students. Back to terminal, so command will be –

# Migration command to create table

$ php artisan make:migration create_students_table

This command will creates a file at location project-root/database/migrations. Filename is something like this – 2020_11_10_010003_create_students_table.php.

Open up the migration file and do the following code –

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name", 120);
            $table->string("email", 50)->nullable();
            $table->string("mobile", 50)->nullable();
            $table->integer("age");
            $table->enum("gender", ["male", "female", "others"]);
            $table->text("address_info");
            $table->timestamp("created_at")->useCurrent();
            $table->timestamp("updated_at")->useCurrent();
        });
    }

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

Next, we need to migrate into database. Back to terminal and type the command –

# Migrate all migrations to database

$ php artisan migrate

It will run all pending migrations & generate tables in database.


Generate Model, Seeder & Factory Class Files

To generate a model, seeder, factory file separately, then we have php artisan command for each. But in case if we need to generate all these by the help of a single command, we also have. Back to terminal

# Command to generate Model, Seeder (s) & Factory (f)

$ php artisan make:model Student -fs

After running this we should have these files and their locations.

  • Student Model at /app/Models/
  • StudentFactory.php at /database/factories/
  • StudentSeeder.php at /database/seeders/

Test data in application we can create by Seeder file only or we can say Factory file only. So let’s see each file and their way to dump test data.


Using Faker Library in Seeder File

Seeder file is used to seed test data for application. In older versions of laravel we need to install faker library for it’s properties and methods. But in the latest version already we have faker library available.

Open StudentSeeder.php from /database/seeders/

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class StudentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = \Faker\Factory::create();

        DB::table("students")->insert([
            "name" => $faker->name(),
            "email" => $faker->safeEmail,
            "mobile" => $faker->phoneNumber,
            "age" => $faker->numberBetween(25, 50),
            "gender" => $faker->randomElement(["male", "female", "others"]),
            "address_info" => $faker->address,
        ]);
    }
}

We have two options available to run this. First we can run directly by passing class flag into command whereas in second we can load seeder class in DatabaseSeeder.php and then run via artisan command.

Running Seeder class directly

# Command to run seeder class file

$ php artisan db:seed --class=StudentSeeder

Above command will insert a single dummy row into database table. If need more then we need to run this command again and again. But better option we can put our code into for loop.

Using DatabaseSeeder to Seed data

Using DatabaseSeeder.php at /database/seeders/ folder

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Database\Seeders\StudentSeeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            StudentSeeder::class
        ]);
    }
}

Now, Command to seed data

# Command to Seed Data

$ php artisan db:seed

Using Factory File to seed Data in Laravel

Factory file we can create via a separate command as well. Command is

# Command to Create a Factory file for a model

$ php artisan make:factory StudentFactory --model=Student

But above we have created factory file when we have created model. Open StudentFactory.php from /database/factories/

<?php

namespace Database\Factories;

use App\Models\Student;
use Illuminate\Database\Eloquent\Factories\Factory;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            "name" => $this->faker->name(),
            "email" => $this->faker->safeEmail,
            "mobile" => $this->faker->phoneNumber,
            "age" => $this->faker->numberBetween(25, 45),
            "gender" => $this->faker->randomElement([
                "male",
                "female",
                "others"
            ]),
            "address_info" => $this->faker->address
        ];
    }
}

Loading Factory File into DatabaseSeeder

Open up DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Database\Seeders\StudentSeeder;
use App\Models\Student;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
         \App\Models\Student::factory(100)->create();
    }
}

Now, Command to seed data

# Command to Seed Data

$ php artisan db:seed

When we run above command, then 100 test rows will be inserted into Model’s respective Database Table.

We hope this article helped you to learn about Laravel 8 Seeder, Factory And generate Test data in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more