Eloquent Cloner Package

Packages

April 8th, 2019

Eloquent Cloner Package

Cloner is a trait for Laravel Eloquent models that lets you clone a model, and it’s relationships, including files. Even to another database.

Here’s a basic example of a model using the Cloneable trait:

class Article extends Eloquent
{
use \Bkwld\Cloner\Cloneable;
}

Here’s how you can clone a model instance, even to another database:

$clone = Article::first()->duplicate();
 
// Cloned to another database by connection name
$clone = Article::first()->duplicateTo('production');

A more advanced example includes defining which relationships cloned along with the model:

class Article extends Eloquent
{
use \Bkwld\Cloner\Cloneable;
 
protected $cloneable_relations = ['photos', 'authors'];
 
public function photos() {
return $this->hasMany('Photo');
}
 
public function authors() {
return $this->belongsToMany('Author');
}
}

Check out the documentation for full details on how you can also define how to clone files attached to a model. You can learn more about this app and check out the source code on GitHub at BKWLD/cloner.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.