Laravel

Cloning Eloquent Models in Laravel

Duplicating an Eloquent model — without its primary key, without timestamps, without accidentally overwriting the original record — is a small problem with a few subtly wrong solutions before you arrive at the right one.


The clone keyword

PHP has a built-in clone keyword that produces a shallow copy of an object. Scalar properties are copied by value; object properties are copied by reference. For a database model, the defaults are almost never right: the copy shares the same id, its exists flag is still true, and any object-type properties point to the same instances as the original.

Read more →