Copy Table Row in Laravel using Eloquent replicate

Copy Table Row in Laravel Using Eloquent

How to Copy Table Row in Laravel and Replicate

This simple article demonstrates of How to Copy Table Row in Laravel.

I came across a problem where in I had to make the exact copy of the Eloquent Model and save it in the database table after changing some of its properties.

Looks like we have a very easy solution available via Eloquent. Although it’s not documented, replicate() method in eloquent does exactly what it’s name suggests.

Eloquent’s replicate()  method can be used to make exact copy of already existing database ro.

Livewire Component Library

Example of replicate() without data modification.

$client = App\Client::find($id);
$newClient = $client->replicate()->save();

This above piece of code will make exact copy of the Client object, and will save it into the database.

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

Example of replicate with data modification.

If you want to make the copy of the row and also change some column data before saving it to the database, You can do it by

$client = App\Client::find($id);
$newClient = $client->replicate();
$newClient->id = $new_id;
$newClient->data = $new_data;
$newClient->save();

Example of replicate with relationships.

If your Model has relationships, that you want to copy too. Then you can make use of push() method provided by the Eloquent.

push() method will fetch you the newly created id for the Model from the database and then you can use the Model object to attach new relationship.

$newClient = $client->replicate();
$newClient->push(); //Push before to get id of $clone
 
foreach($client->roles as $role)
{
    $clone->roles()->attach($role);
}
 
foreach($client->categories as $category)
{
    $client->categories()->attach($category);
}

 

Site Footer