Duplicate a record with Laravel

Iftikhar Ahmed
1 min readJul 9, 2021

Sometimes you need to clone/duplicate database rows, for such Laravel provides a very handy function which is “replicate”. You can call this function on Eloquent model which makes a clone of an existing record.

Let’s take an example.

  1. Create a record:
use App\Models\Address;

$shipping = Address::create([
'type' => 'shipping',
'line_1' => '123 Example Street',
'city' => 'Victorville',
'state' => 'CA',
'postcode' => '90001',
]);

2. Call the replicate method on same model:

$billing = $shipping->replicate();

3. Make changes if required and :

$billing->type = 'billing';
$billing->save();

You can also exclude one or more attributes from being replicated to the new model, you may pass an array to the replicate method:

$billing = $shipping->replicate([
'state' => 'CA',
'postcode' => '90001',
]);

That’s it :)

I hope you had liked the article. Don’t forget to clap and follow me.

If you have any questions please feel free to contact me Twitter, GitHub or join me on Slack #powwow

--

--

Iftikhar Ahmed

My name is Iftikhar Ahmed and I am a Full-Stack Developer, currently living in Karachi, Pakistan.