Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by whitelisting our website.

Copy or duplicate a row in Laravel project

I have been working on an application named “EasySME” with Laravel & MySQL. And a client requested a new feature that he wants to clone/copy/duplicate the existing Invoice. So, I have done a few searches and R&D and found out that Laravel ships with a built-in function called replicate(). Laravel is awesome, you want it and you get the feature :).

You just have to find the record, replicate and save it, and you are done. So, let’s dig down to see a few examples of different scenarios. BTW, we are using the below functions to clone everything! 😀

replicate(): Clone the model into a new, non-existing instance.
save(): Save the model to the database.
push(): Save the model and all of its relationships. 😉

 

 

Let’s start with the simple one, just clone an invoice (/row).

// Find/fetch data
$invoice = Invoice::find($invoiceId);
// Clone existing fetched data
$newInvoice = $invoice->replicate();
// Save the cloned invoice
$newInvoice->save()

 

Now let’s see how to update existing data.
After cloning the data by replicate(), we want to modify the invoice create_at and created_by columns data.

// Clone existing fetched data
$newInvoice = $invoice->replicate();
// Update cloned data
$newInvoice->created_at = now();
$newInvoice->created_by = $userId;

// Save the cloned invoice
$newInvoice->save()

 

How can we clone data with relations?
We can also copy and save every relation which belongs to the invoice(/row). For this, we are using the push() method.

// Find/fetch data
$invoice = Invoice::find($invoiceId);
// Clone existing fetched data
$newInvoice = $invoice->replicate();
$newInvoice->push(); // Push before to get id of $invoice

// Clone the client items/relationships
foreach($invoice->items as $item){

$newInvoice->items()->attach($item);

}

// Save the cloned invoice
$newInvoice->save()

 

You can set the timestamps as the second argument of the attach() method.

 

btw, thanks for spending time on this article. Hope this helps you.  You can share this article with your dearest and nearest everyone.

#HappyCoding, #SharingIsCaringm #LoveToHelp

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress Social Share Plugin powered by Ultimatelysocial