Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone an Eloquent object including all relationships?

Is there any way to easily clone an Eloquent object, including all of its relationships?

For example, if I had these tables:

users ( id, name, email ) roles ( id, name ) user_roles ( user_id, role_id ) 

In addition to creating a new row in the users table, with all columns being the same except id, it should also create a new row in the user_roles table, assigning the same role to the new user.

Something like this:

$user = User::find(1); $new_user = $user->clone(); 

Where the User model has

class User extends Eloquent {     public function roles() {         return $this->hasMany('Role', 'user_roles');     } } 
like image 309
andrewtweber Avatar asked May 27 '14 17:05

andrewtweber


2 Answers

tested in laravel 4.2 for belongsToMany relationships

if you're in the model:

    //copy attributes     $new = $this->replicate();      //save model before you recreate relations (so it has an id)     $new->push();      //reset relations on EXISTING MODEL (this way you can control which ones will be loaded     $this->relations = [];      //load relations on EXISTING MODEL     $this->load('relation1','relation2');      //re-sync everything     foreach ($this->relations as $relationName => $values){         $new->{$relationName}()->sync($values);     } 
like image 59
Sabrina Leggett Avatar answered Sep 24 '22 01:09

Sabrina Leggett


You may also try the replicate function provided by eloquent:

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate

$user = User::find(1); $new_user = $user->replicate(); $new_user->push(); 
like image 31
Piotr Borek Avatar answered Sep 22 '22 01:09

Piotr Borek