Laravel provides us factory and seeder to generate and save dummy data in laravel application quickly. In this how to use factory in laravel tutorial, I will show you laravel factory create multiple records example.

We can generate and save dummy data using factory or seeder. But in this tutorial, I will use factory to create dummy data. In this tutorial, I will create a PostFactory and I will insert dummy data using this factory. Laravel provides make:factory command to create a factory class.

Assume we have a Post model like:

app/Models/Post.php

<?php

namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Item extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'title', 'user_id'
    ];
}

 

Step 1: Create Factory

Now run the below command to create a PostFactory class like:

php artisan make:factory PostFactory

 

And update it like this:

Database\Factories\PostFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Country>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title' => fake()->unique()->paragraph(),
            'user_id' => 1
        ];
    }
}

 

In the previous version of laravel, we can access faker using $this->faker variable like $this->faker->title, But in Laravel 9 version, we can use global faker helper function by using fake(). Now register it inside seeder class like:

Database\Seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Database\Factories\CountryFactory;

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

 

Step 2: Connect Database

After successfully installing the laravel app and then configuring the database setup. We will open the ".env" file and change the database name, username and password in the env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

 

Now run the below command:

php artisan db:seed

 

Now it will insert 10 dummy data in your posts table.

 

Read also: How To Set Default Value In Laravel Migration?

 

Conclusion

I have tried to discuss the clear concept of laravel factory faker. Now we know how to use factory in laravel. Hope this laravel factory create multiple records tutorial will help you.