How to Create Test Data Using Factory in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article provides a summary on how to create test data using Factory in Laravel.
What is a Factory?
A Factory in Laravel is a feature used to create test data (for Seeder or PHP Unit).
By associating it with a model and creating a Factory class beforehand, you can create test data with just a simple line like this:
$user = User::factory()->make();
How to Use Factory
Creating a Table
For this example, let’s assume we already have a users
table where test data will be created.
For information on creating tables, refer to the following article:
⇨ How to Create a Database in Laravel (Migration)
Adding to the User Model (Only for Older Versions)
In current versions, this is already included by default when creating a model.
use Illuminate\Database\Eloquent\Factories\HasFactory;
class User extends Model
{
use HasFactory; //Add this line
}
Creating a Factory File
php artisan make:factory UserFactory
This will generate database/factories/UserFactory.php
.
Next, edit this file.
database/factories/UserFactory.php
As of Laravel 11
public function definition(): array
{
return [
'name' => fake()->name(),
//etc.
];
}
Using the helper function fake()
, this inserts a test data name. By changing name()
to email()
, it will create test data for email addresses instead.
There are many available functions, so check the official documentation to see which ones are offered.
https://fakerphp.org/formatters/internet/
In Laravel 6
use App\Models\User;
protected $model = User::class;
public function definition()
{
return [
'name' => $this->faker->name()
//etc.
]
}
Writing in the Seeder File
Edit database/seeders/DatabaseSeeder.php
:
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
\App\Models\User::factory(100)->create(); //Add this line
}
}
Executing Test Data Generation
Run the following command:
php artisan db:seed
If 100 records have been created in the users
table, you’re all set!
Difference Between Factory and Seeder
Laravel also provides a feature called Seeder.
How to Prepare Test Data in Laravel (Using Seeder)
Since their functions are similar, it’s easy to confuse the two.
Factory is for creating dummy data.
Use Seeder if you want to actually insert test data into the database.
You can define the data for test purposes in Factory and use it as follows:
- If inserting test data into the database, use Seeder (as in this example).
- Use it in PHP Unit testing to create test data.
Conclusion
Factory might feel daunting at first, but it’s a very convenient feature that allows you to create shared data for both test data generation and test code execution. Give it a try!
I aim to keep articles as concise and accessible as possible!