Laravel

Laravel Model Factories Advanced

January 16, 2026 1 min read 18 views

Advanced factories:

States

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

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

Relationships

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

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

Sequences

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

Callbacks

public function configure()
{
    return $this->afterCreating(function (User $user) {
        $user->profile()->create();
    });
}
Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!