Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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.

Comments

Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

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

Web Posts

Search

Page Facebook