What are factories in Laravel?
In Laravel, factories are classes that define how to generate fake data for your models. They are mainly used in combination with seeders or tests to quickly populate your database with realistic-looking dummy data.
Think of factories as blueprints for creating fake model instances.
1. Purpose of Factories
- Quickly generate dummy data for development and testing.
- Useful when you need a lot of test data without manually inserting it.
- Can be used in database seeders or unit tests.
2. Where Factories Are Stored
Factories are stored in the database/factories directory. In Laravel 8 and later, each model usually has its own factory class.
3. Creating a Factory
You can create a factory using Artisan:
php artisan make:factory UserFactory --model=User
This creates a UserFactory.php file linked to the User model.
4. Defining a Factory
Inside the factory, you define the default attributes for the model using Faker, a library for generating fake data:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
protected $model = \App\Models\User::class;
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'password' => bcrypt('password'),
];
}
}
$this->faker->name()→ generates a random name.$this->faker->unique()->safeEmail()→ generates a unique email.
5. Using Factories
Factories can be used in two main ways:
a) Creating a single instance (not saved to DB)
$user = User::factory()->make();
b) Creating and saving to the database
User::factory()->create();
c) Creating multiple records
User::factory()->count(10)->create(); // creates 10 users
6. Using Factories in Seeders
You can combine factories with seeders for bulk database population:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class UsersTableSeeder extends Seeder
{
public function run()
{
User::factory()->count(20)->create(); // creates 20 fake users
}
}
Then run:
php artisan db:seed --class=UsersTableSeeder
✅ Summary:
- Factory = blueprint for generating fake data.
- Seeder = inserts data into the database.
- Together, they make it easy to populate your database with realistic test data.
