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.
In this step, we will get the post record with id
$post = Post::find(1);// selecting post with id of 1
Now, we call the
replicate method on the record.
$newPost = $post->replicate();
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
$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.
View all Courses