Generate Temporary Model Data in Laravel Using replicate()

Duplicate Eloquent models cleanly without manually copying attributes.

  • 28 May, 2026
  • 23 Views

Generate Temporary Model Data in Laravel Using replicate()

Laravel’s replicate() method allows you to clone an existing model instance without copying its primary key or timestamps. This is useful for templates, duplicate records, and draft systems.

Most developers manually copy fields:

$newProduct = Product::create([
    'title' => $product->title,
    'price' => $product->price,
]);

This becomes messy as models grow.

Laravel provides a cleaner solution:

replicate()

Basic Usage

$newProduct = $product->replicate();

Now:

$newProduct->save();

👉 A new record is created with copied attributes.


What replicate() Does

It copies:

  • Attributes
  • Casted values

It does NOT copy:

  • Primary key
  • Created/updated timestamps

Real Project Example

Duplicate a blog post as draft:

$draft = $post->replicate();
$draft->status = 'draft';
$draft->save();

Perfect for:

  • CMS systems
  • Product duplication
  • Reusable templates

Exclude Specific Fields

$product->replicate([
    'slug',
    'sku',
]);

Useful when some fields must remain unique.


Why This Is Useful

It helps you:

  • Avoid manual field copying
  • Duplicate records quickly
  • Simplify template systems
  • Keep code clean

When to Use It

Use replicate() when:

  • Cloning existing models
  • Creating drafts/templates
  • Building duplicate actions


Share: