Laravel Replicate Model with Relationships

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hi Dev’s, Today in this I will show you laravel replicate model with relations. Now, let’s start a new article of replicate model with relations in laravel application. On this article goes to detailed about laravel replicate also with relationships. So we can learn laravel replicate relationships table from here. Now we are looking at a short and good example of replicate laravel with relations table model in larvael 8. Here i will show you Replicate Model with Relationships in laravel.

At my very last articles i already explain with you how to work with replicate() in laravel here: Laravel replicate().  But if we need to work with laravel replicate model with relations then we need to know how can we create duplicate record with relationships tables in larvael applicaton.

Let’s start and see a very simple example.

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

Read Also : Call to undefined function str_slug() in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →