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 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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. 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, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent withSum() and withCount() Example
- Laravel Eloquent firstOrNew Example
- Laravel Eloquent Group By Example
- Delete All Records from Table in Laravel Eloquent
- Laravel Eloquent whereNotNull() Query Example
- Laravel Eloquent whereBetween() Query Example
- Laravel Eloquent whereRaw Condition Example
- Laravel One to One Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial
- Laravel WhereIn() and WhereNotIn() with Subquery Example
- Laravel Where Clause with date_format() Example