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');
}
}
Here is an updated version of the solution from @sabrina-gelbart that will clone all hasMany relationships instead of just the belongsToMany as she posted:
tested in laravel 4.2 for belongsToMany relationships
if you're in the model:
You may try this (Object Cloning):
Since
clone
doesn't deep copy so child objects won't be copied if there is any child object available and in this case you need to copy the child object usingclone
manually. For example:In your case
roles
will be a collection ofRole
objects so eachRole object
in the collection needs to be copied manually usingclone
.Also, you need to be aware of that, if you don't load the
roles
usingwith
then those will be not loaded or won't be available in the$user
and when you'll call$user->roles
then those objects will be loaded at run time after that call of$user->roles
and until this, thoseroles
are not loaded.Update:
This answer was for
Larave-4
and now Laravel offersreplicate()
method, for example:If you have a collection named $user, using the code bellow, it creates a new Collection identical from the old one, including all the relations:
this code is for laravel 5.
Here's another way to do it if the other solutions don't appease you:
The trick is to wipe the
id
andexists
properties so that Laravel will create a new record.Cloning self-relationships is a little tricky but I've included an example. You just have to create a mapping of old ids to new ids and then re-sync.
You may also try the replicate function provided by eloquent:
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate