Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel Model Factories Advanced

Create complex test data with advanced factory techniques.

16 January 20261 min readLaravelاقرأ بالعربية

On this page

  1. States
  2. Relationships
  3. Sequences
  4. Callbacks

Advanced factories:

States

php
public function suspended(): static
{
    return $this->state(['status' => 'suspended']);
}

User::factory()->suspended()->create();

Relationships

php
User::factory()
    ->has(Post::factory()->count(3))
    ->create();

Post::factory()
    ->for(User::factory())
    ->create();

Sequences

php
User::factory()
    ->count(3)
    ->sequence(
        ['role' => 'admin'],
        ['role' => 'user'],
        ['role' => 'guest'],
    )->create();

Callbacks

php
public function configure()
{
    return $this->afterCreating(function (User $user) {
        $user->profile()->create();
    });
}
All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read