Generate Fake Data Using Factory in Laravel 8

Hello devs hope you are well. This article is going to provide some of the most important example laravel 8 factory tinker example. You'll learn from step by step that how to do laravel 8 factory seeder. I will explain step by step laravel 8 factories. In this article, I will implement a laravel 8 factory tutorial. Let's see bellow how to generate laravel 8 dummy record generate example.

As we know testing is very important part of any web application project. Sometime we may require to add many records in your database table, OR maybe thousands of records. Also think about if we may require to check pagination. then we have to add some records for testing. So what you will do it at that that moment ok ?, Do you add manually thousands of records ? What will you do ?. If you add manually thousands of records then it can be take more time, isn't it?

However, Laravel tinker that provide to create dummy records to your model. So in laravel application Laravel provide User model factory created by default. so you can see how to create records using factory bellow:

Generate Dummy Users:

php artisan tinker
  
User::factory()->count(5)->create()

 

This by default created factory of laravel. you can also see that on following url: database/factories/UserFactory.php.

Create Custom Factory:

To create a custom laravel factory, follow the below tips, you can create factory when you create a model. Like

php artisan make:model Product -mf

 

Here m for model and f for factory. Or you can use below tips,.

php artisan make:factory ProductFactory --model=Product

 

Now they created new factory class for product and you can add as bellow code:

database\factories\ProductFactory.php

namespace Database\Factories;
  
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
  
class ProductFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Product::class;
  
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'detail' => $this->faker->text,
        ];
    }
}

 

Generate Dummy Product:

php artisan tinker
Product::factory()->count(500)->create()

 

Read also : Laravel 8 Vue Js Crud Example with Pagination

 

So i hope you created your 500 dummy records on products table.