Skip to main content
Version: 10.x

Factories

Definition#

Factories (are a short name for Model Factories).

Factories are used to generate some fake data with the help of Faker to be used for testing purposes.

Factories are mainly used from Tests.

Principles#

  • Factories SHOULD be created in the Containers.

Rules#

  • All Factories MUST extend from App\Ship\Parents\Factories\Factory.

Folder Structure#

- app
- Containers
- {section-name}
- {container-name}
- Data
- Factories
- UserFactory.php
- ...

Code Samples#

A User Model Factory#

class UserFactory extends Factory
{
protected $model = User::class;
public function definition(): array
{
static $password;
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => $password ?: $password = Hash::make('testing-password'),
'email_verified_at' => now(),
'remember_token' => Str::random(10),
'is_admin' => false,
];
}
}

Usage from Tests or Anywhere Else#

// creating 4 users
User::factory()->count(4)->create();
Further reading

More info at Laravel Docs.

Last updated on by Moslem Deris