I am trying to replicate a record and its relationships in Laravel 8. But I want to keep the original records timestamps. I am able to do this on the main record, but the timestamps on all the relationships get set to the datetime that the record is replicated. I also have some observers set up and I dont want them firing when the replication takes place.
$order = App\Models\Order::with('comments', 'tracking_details')->find(4096);
$clone = $order->replicate()->fill([
'tracking_number' => null,
'created_at' => $order->created_at,
'updated_at' => $order->updated_at,
]);
$clone->saveQuietly();
foreach ($order->comments as $comment) {
App\Models\Comments::withoutEvents(function() use ($clone, $comment) {
$clone->comments()->create($comment->toArray());
});
}
foreach ($order->tracking_details as $details) {
App\Models\TrackingDetails::withoutEvents(function() use ($clone, $details) {
$clone->tracking_details()->create($details->toArray());
});
}
Any help would be greatly appreciated.