Eloquent: how to make a copy of a row

Today I want to tell you about one “hidden” Laravel feature which is in the system but not in documentation – replicate. This function allows you to make a copy of a row in the fastest way possible.

In the database we have a task which looks like this:

ReplicateDatabaseSingle

And then we run the following code to duplicate a single row:

We should see that our database row was replicated with new id and updated timestamps:

ReplicateDatabaseMulti

And that’s it! With a few lines of code you can replicate a lot of data. This method works with loops too, so you can use this method to duplicate all of our entries.

If you want to get new copy row ID

$new_ID = $newTask->id

Leave a Reply

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