Clone or Duplicate a Database Record in Laravel

If you need to duplicate or clone a database record and wondering how to achieve such functionality, then you are at right place. Here I will show you with an example.

To duplicate or clone a database record Laravel provides a very handful function called replicate(). The replicate function will take the Eloquent model and makes a copy of that model so one can make desired change and save it. Lest see the example below to find out how we can use this.

Consider you have a post model and you are trying to make a copy of article on your Post model and publish it again as another post/article after making some changes. To do that lets get the desired article from your post model.

$post = Post::find($id); 

Now call the replicate() method/function on it, and assign it to another variable.

$new_post = $post->replicate(); 

Its time to make your changes on $post model, and save it. This will create another post with the changes on the previous post.

 $new_post->title = "new duplicate title";
 $new_post->updated_at = Carbon::now();
 $new_post->save(); 

The above code all together will look like:

$post = Post::find($id);
$new_post = $post->replicate();
$new_post->title = "new duplicate title";
$new_post->updated_at = Carbon::now();
$new_post->save(); 

The replicate method is very helpful for quick cloning or duplicating a database record. Hope you get something useful. Thanks for reading.

Comments :

  • Addison Stephenson 4 months ago

    Duis qui quis sit a
  • Arun pradhan 4 months ago

    Thanks for the post. please write a post on how to use Eloquent Query scopes.
  • Arun pradhan 4 months ago

    Thanks for the post. please write a post on how to use Eloquent Query scopes.
  • Arun pradhan 4 months ago

    Thanks for the post. please write a post on how to use Eloquent Query scopes.
  • Arun pradhan 4 months ago

    Thanks for the post. please write a post on how to use Eloquent Query scopes.