Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

Eloquent: how to make a copy of a row

January 19, 2016
1 min read
Today I want to tell you about one "hidden" Laravel feature which is in the system but not in documentation - replicate. This function allows you to make a copy of a row in the fastest way possible. To start with, we are going to have a table:
Schema::create('tasks', function (Blueprint $table) {
    $table->increments('id');
    $table->string('task');
    $table->text('description');
    $table->timestamps();
    $table->softDeletes();
});
And a model:
class Tasks extends Model
{
    use SoftDeletes;
    protected $table = 'tasks';
    protected $fillable = ['task', 'description'];
}
In the database we have a task which looks like this: ReplicateDatabaseSingle And then we run the following code to duplicate a single row:
$tasks = Tasks::find(1);
$newTask = $tasks->replicate();
$newTask->save();
We should see that our database row was replicated with new id and updated timestamps: ReplicateDatabaseMulti And that's it! With a few lines of code you can replicate a lot of data. This method works with loops too, so you can use this method to duplicate all of our entries.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.