DEV Community

Ibrahim
Ibrahim

Posted on

How to Duplicate a Laravel Model

Laravel provides the replicate method, which is used to duplicate a model.

For example, there is an Order model. Suppose we want to create a feature that duplicates an order. This feature can be created by using the replicate method on the Order model.

<?php

use App\Models\Order;

class OrderController {
    public function duplicateOrder(Order $order) {
        $newOrder = $order->replicate();

        $newOrder->duplicated_from_id = $order->id;
        $newOrder->save();

        return $newOrder;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, after the model is duplicated, we can modify the attributes of the new model before saving it.

The duplicated model is not automatically saved in the database; you need to call the save method manually.

If there are any properties in the original model that you don't want to duplicate, you can exclude them by passing their names as an array to the replicate method.

For example:

<?php

use App\Models\Order;

class OrderController {
    public function duplicateOrder(Order $order) {
        $newOrder = $order->replicate([
            'validated_at',
            'order_status'
        ]);

        $newOrder->duplicated_from_id = $order->id;
        $newOrder->save();

        return $newOrder;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the validated_at and order_status properties will not be copied to the new model.

Top comments (0)