Duplicating database records is a common task when working with Laravel applications. Whether you need to create a copy of a blog post, product listing, or any other record, Laravel makes this process simple with its built-in replicate method.
In this article, I’ll show you how to use replicate to clone an Eloquent model easily. With just a few lines of code, you can duplicate records while making any necessary modifications before saving.
How to Duplicate Database Record with Laravel 11
Example - 1:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
class CategoryController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$category = Category::find(1);
$newCategory = $category->replicate()->save();
dd($newCategory);
}
}
Example - 2:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
class CategoryController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$category = Category::find(1);
$newCategory = $category->replicate();
$newCategory->name = "Cloth";
$newCategory->save();
dd($newCategory);
}
}
Example - 2:
use App\Models\Address;
$shipping = Address::create([
'type' => 'shipping',
'line_1' => '123 Example Street',
'city' => 'Victorville',
'state' => 'CA',
'postcode' => '90001',
]);
$billing = $shipping->replicate()->fill([
'type' => 'billing'
]);
$billing->save();
You might also like: