Laravel Replicate Model with Relationships Example

By Hardik Savani | March 26, 2021 | Category : Laravel


Now, let's see article of laravel replicate model with relations. This article goes in detailed on laravel replicate with relationships. you will learn laravel replicate relationships table. We will look at example of replicate laravel with relations table model.

i already explain you how to work with replicate() here: Laravel replicate(). but if you need to work with laravel replicate model with relations then how can you create duplicate record with relationships tables.

Let's see two 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);

}

}

i hope it can help you...




Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: