DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Clone Eloquent Models Selectively

Sometimes, you may need to duplicate a model instance and create a new one with some custom changes. Instead, you can use Laravel's built-in replicate method:

use App\Models\Address;

$shipping = Address::create([
    'type'     => 'shipping',
    'line_1'   => '123 Example Street',
    'city'     => 'Victorville',
    'state'    => 'CA',
    'postcode' => '90001',
]);

// Create a replicated instance of the address without saving it
$replicatedAddresss = $shipping->replicate();
Enter fullscreen mode Exit fullscreen mode

The previous code creates a new address instance but does not save it to the database. Before saving, you can modify any attributes as needed:

...

$replicatedAddresss->type = 'billing';

// Save the replicated instance to the database
$replicatedAddresss->save();
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can replace the previous line where the property is assigned with the fill method:

...

$replicatedAddresss = $shipping->replicate();

$replicatedAddresss->fill(['type' => 'billing'])->save();
Enter fullscreen mode Exit fullscreen mode

On top of that, you can exclude specific attributes from being replicated by passing them as an array to the replicate method:

$shipping = Address::create([
    'type'     => 'shipping',
    'line_1'   => '123 Example Street',
    'city'     => 'Victorville',
    'state'    => 'CA',
    'postcode' => '90001',
]);

$shipping->replicate([
    'line_1',
    'state'
]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)