how to create a Laravel replicate relationships table

Let us now look at the article of laravel replicate model with relations. This article discusses laravel replicate with relationships in depth. You will learn how to create a Laravel replicate relationships table. We’ll look at an example of replica laravel with a relations table model.

I’ve already explained how to use replicate() here: Laravel replicate (). But how can you create duplicate records with relationships tables if you need to work with a Laravel replicate model with relations?

Let’s look at two simple examples.

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

Controller Code

<?php
  
namespace App\Http\Controllers;
  
use App\Models\Category;
  
class SignaturePadController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $cat = Category::find(16);
        $newCat = $cat->replicateRow();
  
        dd($newCat);
    }
}

All the best nerd!

Leave a Reply