How to duplicate a database record in Laravel

Overview

Duplicating a database record can be very important. For instance, it can be important when you have a blog post that you want to publish again to see if user interaction increases or decreases.

In this shot, we will learn how to use the replicate() method to replicate data records.

Step 1

In this step, we will get the post record with id 1.

$post = Post::find(1);// selecting post with id of 1

Step 2

Now, we call the replicate method on the record.

$newPost = $post->replicate();

Step 3

You can make any changes you like. In this example, we change the date to today’s date.

$newPost->created_at = Carbon::now(); // changing the created_at date
$newPost->save();// saving it to the database

Complete code

$post = Post::find(1);
$newPost = $post->replicate();
$newPost->created_at = Carbon::now();
$newPost->save();

The steps above can be followed and executed from your controller without the use of any third-party packages.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources