Moving data from one table to another is a common task when managing databases in Laravel applications. Laravel provides an easy way to accomplish this using the replicate() method along with setTable().
In this article, I’ll show you how to transfer records between tables with practical examples. Whether you're restructuring your database or archiving old records, you’ll find this guide helpful.
Laravel 11 Move Data from One Table to Another Table
Example 1: Laravel Move One Row to Another Table
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$user = User::find(1);
$user->replicate()
->setTable('inactive_users')
->save();
}
}
Example 2: Laravel Move Multiple Rows to Another Table
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
User::select("*")
->where('last_login','<', now()->subYear())
->each(function ($user) {
$newUser = $user->replicate();
$newUser->setTable('inactive_users');
$newUser->save();
$user->delete();
});
}
}
Example 3: Laravel Copy Data to Same Table
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$product = Product::find(5);
$newProduct = $product->replicate()->save();
dd($newProduct);
}
}
You might also like:
In this article, we will see carbon add years to date in laravel 9. Carbon provides addYear() and addYears() functi...
Nov-21-2022
In this article, we will see laravel 9 pluck method example. The pluck method retrieves all of the v...
Jul-20-2022
In this tutorial, I will show you laravel 9 toastr notifications example. Using toastr.js you can display a success...
Feb-23-2022
In this post, I will show you how to break lines for Textarea in laravel blade. Many times when you save...
Jul-26-2020