Laravel 11 Replicate Model with Relationships

In Laravel, duplicating a model is straightforward with the replicate() method. However, when it comes to replicating models along with their relationships, the process requires additional steps. In this article, I’ll show you how to clone a model with its related records in Laravel 11.

Whether you're dealing with one-to-many, many-to-many, or other relationships, you’ll learn how to preserve related data while duplicating the main record.

Laravel 11 Replicate Model with Relationships

Laravel 11 Replicate Model with Relationships

 

app/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'price', 'slug', 'category_id'
    ];
}

app/Models/Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

    use HasFactory;
    /**
    * Get the comments for the blog post.
    */

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    /**
    * Get the comments for the blog post.
    */

    public function replicateRow()
    {

        $clone = $this->replicate();
        $clone->push();         

        foreach($this->products as $product)
        {
           $clone->products()->create($product->toArray());
        }

       $clone->save();
    }
}

App/Http/Controllers/CategoryController

<?php

namespace App\Http\Controllers;

use App\Models\Category;

class CategoryController extends Controller
{

    /**
    * Write code on Method
    *
    * @return response()
    */

    public function index()
    {

        $cat = Category::find(5);
        $newCat = $cat->replicateRow();

        dd($newCat);
    }
}

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS