ItSolutionStuff.com

Laravel Replicate Model with Relationships Example

By Hardik Savani • November 5, 2023
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

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent withSum() and withCount() Example

Read Now →

Laravel Eloquent firstOrNew Example

Read Now →

Laravel Eloquent Group By Example

Read Now →

Delete All Records from Table in Laravel Eloquent

Read Now →

Laravel Eloquent whereNotNull() Query Example

Read Now →

Laravel Eloquent whereBetween() Query Example

Read Now →

Laravel Eloquent whereRaw Condition Example

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel WhereIn() and WhereNotIn() with Subquery Example

Read Now →

Laravel Where Clause with date_format() Example

Read Now →