Clone an Eloquent object including all relationships?

后端 未结 10 689
我寻月下人不归
我寻月下人不归 2020-12-01 01:24

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          


        
10条回答
  •  不思量自难忘°
    2020-12-01 01:50

    You may try this (Object Cloning):

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

    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 using clone manually. For example:

    $user = User::with('role')->find(1);
    $new_user = clone $user; // copy the $user
    $new_user->role = clone $user->role; // copy the $user->role
    

    In your case roles will be a collection of Role objects so each Role object in the collection needs to be copied manually using clone.

    Also, you need to be aware of that, if you don't load the roles using with 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, those roles are not loaded.

    Update:

    This answer was for Larave-4 and now Laravel offers replicate() method, for example:

    $user = User::find(1);
    $newUser = $user->replicate();
    // ...
    

提交回复
热议问题