Duplicate or Clone a database record with Laravel


March 15th, 2021

Duplicate or Clone a database record with Laravel

Have you ever needed to duplicate or clone a database record? Laravel provides a very handy function for this called replicate which will take an Eloquent model and make a copy so you can then make changes and save it.

Here's an example of how you might use this. Let's pretend you have a blog post and you want to make a copy of it to publish again. First grab the original model:

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

Next, call the replicate method on it:

1$newPost = $post->replicate();

Now, you can make any changes you need to the model and then resave it.

1$newPost->created_at = Carbon::now();

All together it would look like this:

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

This replicate method is really helpful for quickly cloning or duplicating a database record.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.