Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 8+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 25 Mar, 2026
  • 24 Views
  • Create or fetch data in one clean line without writing extra checks.

Avoid Duplicate Records in Laravel Using firstOrCreate()

The Problem: Duplicate Data

In real Laravel applications, you often face situations like:

  • Creating tags
  • Saving categories
  • Adding users or settings

Without proper checks, duplicate records can be created.


The Traditional Way

$tag = Tag::where('name', $name)->first();

if (! $tag) {
    $tag = Tag::create(['name' => $name]);
}

Works — but not clean.


The Laravel Way: firstOrCreate()

$tag = Tag::firstOrCreate([
    'name' => $name
]);

Laravel:

  • Checks if record exists
  • Creates it if not
  • Returns the model

All in one line.


Real Project Example

Imagine saving product tags:

foreach ($tags as $tagName) {
    $tag = Tag::firstOrCreate([
        'name' => $tagName
    ]);

    $product->tags()->attach($tag->id);
}

No duplicates. Clean logic.

Share: