How to us factory in laravel?

In Laravel, a factory is a class that allows you to define a set of default attributes for each of your Eloquent models. These factories are primarily used when testing your application or seeding your database. Instead of manually specifying the value of each column, you can use factories to automatically generate and insert a few records into your database.

Step 1 : Create Model, Migration and Controller

We will create a model, migration and controller named post, To do that we will use -mcr command, This single command will generate model, migration and controller.

php artisan make:model Post -mcr

First lets create a resource route in web.php

Route::resource('post', PostController::class);

Now lets create a migration, You will get a migration file in :

/database/migrations/_create_posts_table.php

In migration file we will add title, slug and content field.

public function up(): void
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('slug');
        $table->text('content')->nullable();
        $table->timestamps();
    });
}

Now we will run migration command which will create a table in database

php artisan migrate
Step 2 : Create Factory

Now we will generate a factory and use --model=Post, This will connect factory to Post model.

php artisan make:factory PostFactory --model=Post

A file name PostFactory will be created in /database/factories/PostFactory.php.

In this code, the `definition` method returns an array of default values for the `Post` model. The `faker` property is an instance of the Faker PHP library, which is used to generate random data.


use Illuminate\Support\Str;


public function definition(): array
{
    $title = $this->faker->sentence($nbWords = 6, $variableNbWords = true);
    $slug = Str::slug($title);

    return [
        'title' => $title,
        'slug' => $slug,
        'content' => $this->faker->text($maxNbChars = 2000)
    ];
}

Now you need to connect factory with model, So open post model which is located in :

/app/Models/Post.php


Note : If you are unable to connect factory with model then you need to declare $model variable above the definition function in PostFactory.php 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    
    protected $fillable = ['title','slug','content'];
}
//PostFactory.php
protected $model = Post::class;
Step 3 : Usage

We will use Laravel Tinker, But if you do not want to use tinker you can create a custom command to run factory, If you dont know how to create custom command than please check this post.


Laravel Tinker is a powerful REPL (Read-Eval-Print Loop) tool included with Laravel that allows you to interact with your Laravel application from the command line. It's commonly used for interaction with Eloquent ORM, jobs, events, etc.


Tinker allows you to run code within the context of your application. This means you can interact with your database, perform CRUD operations, and even write PHP code directly in the command line. 


To enter the Tinker environment, you can run the command below.

php artisan tinker

After tinker is started you can use the code below, this will create 10 fake data in post table, You can create as much as you like, Just change the count. 

Post::factory()->count(10)->create()