How To Replicate Model With Its Relationship In Laravel

Hello artisan,

In this tutorial, I will show you how to replicate a model with the nested relationship. There are many ways to do that. But I will show you a simple way of doing that. We may create an unsaved copy of an existing model instance using the replicate method. This method is useful when we have model instances that share many of the same attributes:

use App\Models\Address;
$shipping = Address::create([
    'type' => 'shipping',
    'line_1' => '123 Example Street',
    'city' => 'Victorville',
    'state' => 'CA',
    'postcode' => '90001',
$billing = $shipping->replicate()->fill([
    'type' => 'billing'


To exclude one or more attributes from being replicated in the new model, we may pass an array to the replicate method:

$flight = Flight::create([
    'destination' => 'LAX',
    'origin' => 'LHR',
    'last_flown' => '2020-03-04 11:00:00',
    'last_pilot_id' => 747,
$flight = $flight->replicate([


Replicate (Duplicate) Eloquent Model With Relations

Now in this example, we will replicate a model with its relationship. See the below example to understand:

public function replicateWithRelations(QuestionCategory $questioncategory)
  $newCategory = $questioncategory->replicate();
  $newCategory->name = "Kopyası: ".$questioncategory->name;

  $questioncategory->relations = [];

  //load relations on EXISTING MODEL

  //re-sync everything
  foreach ($questioncategory->getRelations() as $relationName => $values){

  return redirect()->route('neon.questioncategory.edit',$newCategory->id)->withSuccess("Kategori başarıyla kopyalandı");


Read also: Some Laravel Model Properties Which You Need To Know


Hope it can help you.

#laravel #laravel-9x