0
0
LaravelHow-ToBeginner · 3 min read

How to Use Factory in Test in Laravel for Easy Data Creation

In Laravel tests, use Model::factory() to create model instances easily. You can call create() to save to the database or make() to create without saving. This helps generate test data quickly and cleanly.
📐

Syntax

Laravel factories use the factory() method on a model to generate test data. The common methods are:

  • Model::factory()->make(): Creates a new model instance but does not save it to the database.
  • Model::factory()->create(): Creates and saves the model instance to the database.
  • Model::factory()->count(n)->create(): Creates and saves n instances.

You can also customize attributes by passing an array to create() or make().

php
User::factory()->make();
User::factory()->create();
User::factory()->count(3)->create();
User::factory()->create(['name' => 'Alice']);
💻

Example

This example shows how to use a factory in a Laravel test to create a user and check the database.

php
<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserFactoryTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_factory_creates_user()
    {
        // Create and save a user to the database
        $user = User::factory()->create(['name' => 'Test User']);

        // Assert the user exists in the database
        $this->assertDatabaseHas('users', [
            'name' => 'Test User',
            'email' => $user->email,
        ]);
    }
}
Output
PASS: The test confirms a user named 'Test User' is saved in the database.
⚠️

Common Pitfalls

Common mistakes when using factories in Laravel tests include:

  • Not using RefreshDatabase trait, causing test data to persist and affect other tests.
  • Using make() when you need the model saved in the database for assertions.
  • Not importing the model or factory namespace correctly.
  • Forgetting to define a factory for the model or using an outdated factory syntax.
php
<?php
// Wrong: Using make() but asserting database
$user = User::factory()->make();
$this->assertDatabaseHas('users', ['email' => $user->email]);

// Right: Use create() to save before asserting
$user = User::factory()->create();
$this->assertDatabaseHas('users', ['email' => $user->email]);
📊

Quick Reference

MethodDescription
Model::factory()->make()Create model instance without saving to database.
Model::factory()->create()Create and save model instance to database.
Model::factory()->count(n)->create()Create and save multiple instances.
Model::factory()->create(['field' => 'value'])Create with custom attributes.

Key Takeaways

Use Model::factory()->create() to generate and save test data in Laravel tests.
Use make() when you want a model instance without saving it to the database.
Always use the RefreshDatabase trait to keep tests isolated and clean.
Customize factory data by passing an array of attributes to create() or make().
Ensure your model has a factory defined using Laravel's modern factory classes.