$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[June 23, 2024] Laravel

Laravel Model Factories: Relationships

Laravel Model Factories: Relationships

────────────────────────────────────────────────────────

Laravel Model Factories: Relationships

Tip: has() for HasMany

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

Creates a post with 3 comments.

Gotcha: for() for BelongsTo

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

Creates the parent post first, then the comment.

Tip: Factory States

public function published(): static
{
    return $this->state(['published' => true, 'published_at' => now()]);
}

Usage: Post::factory()->published()->create().

Gotcha: hasAttached() for BelongsToMany

User::factory()->hasAttached(Role::factory()->count(2))->create();

Creates a user with 2 roles attached.

Tip: sequence() for Variation

User::factory()->count(3)->state(new Sequence(
    ['role' => 'admin'],
    ['role' => 'user'],
    ['role' => 'moderator'],
))->create();

Gotcha: afterMaking vs afterCreating

afterMaking runs before save. afterCreating runs after save. Use afterCreating for attaching relations.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

The Laravel ecosystem moves fast, and keeping up with every new first-party package can feel overwhelming. I've found that mastering the core — the container, Eloquent, queues, and the HTTP layer — pays far more dividends than chasing every new release. Architecture and debugging skills transcend framework versions. When I mentor developers, I focus on understanding the 'why' behind Laravel's design choices rather than memorizing syntax. The framework changes; the principles don't.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts