CLONE ELOQUENT MODELS SELECTIVELY

Jun 13, 2025 Copy Link

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();

 

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();

 

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

 

...

$replicatedAddresss = $shipping->replicate();

$replicatedAddresss->fill(['type' => 'billing'])->save();

 

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'
]);

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE