Using wasRecentlyCreated to Conditionally Save Metadata

📖 1 minute read

When using firstOrCreate() in seeders or migrations, check wasRecentlyCreated before saving metadata. This prevents overwriting existing relationships when re-running seeders.

❌ Before: Always Overwrites

public function run(): void
{
    foreach ($data as $item) {
        $record = Model::firstOrCreate(['name' => $item['name']]);
        $record->saveMeta('parent_id', $parentId); // Always overwrites!
    }
}

✅ After: Conditional Save

public function run(): void
{
    foreach ($data as $item) {
        $record = Model::firstOrCreate(['name' => $item['name']]);
        if ($record->wasRecentlyCreated) {
            $record->saveMeta('parent_id', $parentId); // Only on create
        }
    }
}

Why This Matters

Seeders should be idempotent — safe to run multiple times without side effects. The wasRecentlyCreated property tells you whether firstOrCreate() created a new record or found an existing one.

This is especially important when:

  • Re-running seeders in development
  • Deploying database changes that include seed data
  • Populating initial relationships without overwriting user modifications

The pattern ensures you populate data for new records while leaving existing ones untouched.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *