Skip to main content
Category:

How to make cloning of Models in Laravel

 

Example how to clone of Models in Laravel:

If find yourself needing to clone a row, maybe change a few attributes but you need an efficient way to keep things DRY. Laravel provides a sort of 'hidden' method to allow you to do this functionality. Though it is completely undocumented, you need to search through the API to find it.

Using $model->replicate() you can easily clone a record.

$book = Book::find(5);
$cloneBook = $book->replicate();

Also you can add custom attributes to this new model like this:


$cloneBook->nbre += 1;
$cloneBook->save();

The above would find a book that has an ID of 5, then clones it.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook