Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
communitycreator

How to duplicate a database record in Laravel

Chinweuba Elijah Azubuike

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.

RELATED TAGS

laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring