Laravel Replicate Model with Relationships Example

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 AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

class Product extends Model

{

use HasFactory;

protected $fillable = [

'name', 'price', 'slug', 'category_id'

];

}

app/Models/Category.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

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 AppHttpControllers;

use AppModelsCategory;

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…

Leave a Comment