Eloquent Cloner Package

Packages

April 8th, 2019

laravel-cloner.png

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:

1class Article extends Eloquent
2{
3 use \Bkwld\Cloner\Cloneable;
4}

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

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

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

1class Article extends Eloquent
2{
3 use \Bkwld\Cloner\Cloneable;
4
5 protected $cloneable_relations = ['photos', 'authors'];
6
7 public function photos() {
8 return $this->hasMany('Photo');
9 }
10
11 public function authors() {
12 return $this->belongsToMany('Author');
13 }
14}

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.