php

Laravel 9 Factory With Example

“Today, we are going to learn about Laravel 9 Factories and seeder with an example. Before starting this project, we need to know why we need factories? When we need to add a number of fake data or dummy data to our Laravel project for testing purposes, then we use factories. Now we will give an example project that shows you how to generate fake data for our project.”

Project Requirements are Given Below

  1. MySQL 5.6+
  2. MariaDB 10.2+
  3. PostgreSQL 9.4+
  4. SQLite 3.8.3+
  5. SQL Server 2008+
  6. PHP 8.1 

Project Working Process

  1. Step 1 – Installing Laravel 9
  2. Step 2 –Creating a database and connecting the database with the project
  3. Step 3- Create a Model for the project
  4. Step 4- Generate Dummy data for the project 
  5. Step 5- Finally, Run and test the project

Step 1 – Installing Laravel 9

In step one, we need to go into the project directory and run the command given below-

composer create-project laravel/laravel factory

cd factory

php artisan serve

Step 2 – Creating a Database and Connecting the Database With the Project

In step two, we need to create a database in our phpMyAdmin; for this factory project, we will use MariaDB /MySQL 5.7. Now, we need to copy the below link and paste it into our browser, then click the home button on the left side. Then click in databases there we will find Create Database area. Then we need to put our database name there. We will use “factory” as a database name.

localhost/phpMyAdmin

Now we will connect the database with our project-

Go to the .env file and configure the Database

DB_CONNECTION=MySQL

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=factory (Your database name)

DB_USERNAME=root (Your Database User name)

DB_PASSWORD= (Your Database Password)

Our Database connection done

Step 3- Create a Model for the Project

In Step Three, we will create a table called dummy_data table with migration using this commend

php artisan make:model Dtaxt -m


Once the model created then needs to open

“database\migrations\2022_06_28_074351_create_dtaxts_table.php”


Now add these two lines there

$table->string('name')->nullable();

$table->string('details')->nullable();

Here is the Code

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

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

    /**
     * Run the migrations.
     *
     * @return void
     */

    public function up()
    {


Schema::create('dtaxts', function (Blueprint $table) {

            $table->id();

            $table->string('name')->nullable();

            $table->string('details')->nullable();

            $table->timestamps();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */

    public function down()
    {


Schema::dropIfExists('dtaxts');

    }

};

Now, need to open database\factories\DtaxtFactory.phpand add the flowing code

protected $fillable = [

              'name',
              'details'
    ];


 

Here is the file code

namespace App\Models;

 

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

 

class dummy_data extends Model

{

    use HasFactory;
    protected $fillable = [
              'name',
              'details'
    ];


}

Now need to run

php artisan migrate

Step 4- Generate Dummy Data for the Project

Now, need to create a factory for our project with this command line-

php artisan make:factoryDtaxtFactory --model=Dtaxt

Now, Go to factory\factory\database\factories\DtaxtFactory.php

Add this line

'name' => $this->faker->name(),

'details' => $this->faker->text(),

Here is the code

namespace Database\Factories;

 

use Illuminate\Database\Eloquent\Factories\Factory;

 

/**

 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\dummyData>

 */


class DummyFactory extends Factory

{

    /**
     * Define the model's default state.
     *


     * @return array<string, mixed>

     */


 

     public function definition()

     {

        return [

           'name' => $this->faker->name(),

           'details' => $this->faker->text(),

        ];
    }
}

Step 5- Finally, Run and Test the Project

In Step Five, our project is almost ready; now need to perform

Before giving any commend, we need to run this

  • composer dumpautoload

then Run

  • php artisan tinker

then type

>>Dtaxt::factory()->count(10)->create();   

Result –

PS C:\Users\User\Documents\GitHub\-Laravel-Factory-Example>php artisan tinker

Psy Shell v0.11.5 (PHP 8.1.3 — cli) by Justin Hileman

>>>Dtaxt::factory()->count(10)->create();

=> Illuminate\Database\Eloquent\Collection {#3570

     all: [
       App\Models\Dtaxt {#3574
        name: "Mrs. Lura Hirthe",
         details: "Deseruntsintrepellendusofficiisfacere. Nihil sed officia ab id. Dolores quia error voluptatibussequi.",
updated_at: "2022-07-04 12:47:02",
created_at: "2022-07-04 12:47:02",
         id: 31,
       },
       App\Models\Dtaxt {#3572
        name: "Dulce Rogahn",
         details: "Id voluptas ipsum aliquidsequi ab. Autistecumque qui aliquidomnisincidunt. Qui et autem minima veritatis. Corporis magniquis error aut labore rerum.",
updated_at: "2022-07-04 12:47:03",
created_at: "2022-07-04 12:47:03",
         id: 32,
       },
       App\Models\Dtaxt {#3575
        name: "Mr. Morris Bahringer",
         details: "Qui eum qui unde nemo. Ad aliquamquiautquiacumque.",
updated_at: "2022-07-04 12:47:03",
created_at: "2022-07-04 12:47:03",
         id: 33,
       },
       App\Models\Dtaxt {#3576
        name: "Francisco Bechtelar",
         details: "Sapiente rem et earum et. Assumenda id natuseateneturpossimus sed. Autlaborumaspernaturoptioconsequuntur.",
updated_at: "2022-07-04 12:47:03",
created_at: "2022-07-04 12:47:03",
         id: 34,
       },
       App\Models\Dtaxt {#3577
        name: "Sadye Turcotte",
         details: "Excepturi in sit sed nullavoluptatemnecessitatibus nobis omnis. Sint autem dignissimospraesentiumadipisci hic sint. Sed eiusdebitis nihil quaeratexplicabopariatur.",
updated_at: "2022-07-04 12:47:03",
created_at: "2022-07-04 12:47:03",
         id: 35,
       },
created_at: "2022-07-04 12:47:03",
         id: 39,
},       App\Models\Dtaxt {#3582
        name: "Celestino Strosin",
         details: "Excepturi nihil nostrum cumque facilis autem suscipit. Nam enimquamducimuscorrupti culpa magni. Officiis sit quiarationeenim sit voluptates.",
updated_at: "2022-07-04 12:47:03",
created_at: "2022-07-04 12:47:03",
         id: 40,
       },
     ],
   }
 

>>>

Conclusion

Finally, our project was completed successfully. Hope this factory project will help the learner to understand the Laravel 9 factory. Using this project, you can create and import dummy data to your project.

About the author

Rakhibul Hasan

This is Rakhibul Hasan CEO and Founder of Clipping Path Creative Inc. We provide 100% handmade photo editing services to use Adobe Photoshop. Our services are Clipping path, Background removal, Color correction, Photo retouching, Car photo editing, drop shadow etc. Also we offer an image as a trial to judge our quality. So contact us and get instant reply.