Laravel Eloquent – make a copy of a row

Today I would like to write about one of the little-known features of laravel eloquent called “replicate”. To copy everything from existing row we just need to call replicate() method on the eloquent modal object after selecting a row. Lets see the example, Here Post is my modal, posts is my DB table with sample data and I am selecting single row on top of that I am calling replicate() to copy the row, then I am calling save method to save(insert) data in the DB table.

replicate() – Clone the model into a new, non-existing instance.
save() – Save the model to the database.
push() – Save the model and all of its relationships.

Clone model and modify existing data

While coping existing records(posts), if you what to modify existing data, store the replicated data in a variable then make the changes as shown below –

This method works with loops and relationships too, so you can use this method to duplicate all of our entries.

Clone model and it’s relationship

Here each post belongs to tags and categories, lets copy everything and save it to database.

NOTE- you may set the timestamps to the second argument of attach()

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 vote
Article Rating
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Victor Halauko
Victor Halauko
4 years ago

$duplicatePost = $post->replicate();
$duplicatePost = $post->name . ” ” . $post->id;

Love Lumar
Love Lumar
2 months ago

Hi arjun can send your email id Show that we can discuss some of the doubts and we are doing country wise website.

Girish Panday
Girish Panday
19 days ago

Hi arjun,

Can you guide me to run my scheduler to make expiry my post after the given time interval for post.

DMCA.com Protection Status
4
0
Would love your thoughts, please comment.x
()
x