Duplicate row with relationship in Laravel 5

To duplicate row in Laravel 5 is easy as 123, where in fact you don’t have to do as much as it has a builtin method to do so.

To copy record you can use the replicate() method.

So for example, we pickup a question by querying its id, and then replicate it. Then you will have the exact copy of that record you are querying.

But what if you want to duplicate a record and all those records related to it?

Let’s say question belongs to quiz. We duplicate the quiz and then we want also all questions inside the quiz to be duplicated as well.

We can accomplish such by looping like below

First we copy first the quiz, which we find through its id. We put it in a variable then we replicate the quiz and save it.

Notice:

Since the newly created quiz has its new id, we assign it manually in the questions before saving it, this will make sure that the questions created is part of the duplicated quiz.

Next we loop through the variable we just made, we invoke the same code as we did in the quiz. You will now have the same records.

Note: Your tables should be connected with belongsTo and hasMany() relationship in order to use the with() method.

What if you still have third level? Like Quiz has many questions and questions has many choices?

Then just repeat the steps.

Sharing is caring!