Laravel

How to generate dummy data using factory in laravel

Laravel

How to generate dummy data using factory in laravel

If you want to start writing some tests for your Laravel project then chances are you will need to write some factories at some point.

Instead of manually making an array you can make a factory class. There is an artisan command that will allow you to easily make a factory for your product model.

php artisan make:factory PostFactory --model=Post

This will generate a new PostFactory.php file in the database/factories directory and associate it with your Post model.

<?php

namespace Database\Factories;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'content' => $this->faker->text(rand(500,2000)),
            'tags' => $this->faker->text(5).','.$this->faker->text(5).','.$this->faker->text(5),
            'status' => rand(0,1),
            'published_date' => $this->faker->dateTime()
        ];
    }
}

Generate Dummy Product:

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

Using Faker you can be used to generate the following data types:

Numbers
Lorem text
Person i.e. titles, names, gender etc.
Addresses
Phone numbers
Companies
Text
DateTime
Internet i.e. domains, URLs, emails etc.
User Agents
Payments i.e. MasterCard
Colour
Files
Images
uuid
Barcodes

Hopefully this article has given you some ideas of how you can get started with using factories in your tests and make writing tests a bit easier in future.