Laravel Move Data from One Table to Another Table Example

By Hardik Savani November 5, 2023 Category : Laravel

Hello,

This tutorial shows you laravel move data from one table to another. This post will give you a simple example of laravel migrate data from one table to another table. I would like to share with you how to move data one table to another table in laravel. you will learn how to migrate data one table to another table in laravel.

Laravel provides replicate() eloquent method to move records from one table to another table. we will use replicate() with setTable() method to migrate data one table to another. I will give you the following three examples:

you can easily use replicate() from laravel 8 version.

Example 1: Laravel Move One Row to Another Table

Here, we will use replicate() and setTable() method to move one record 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 Row to Another Table

Here, we will use replicate() and setTable() method to move multiple records 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::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

Here, we will use replicate() and save() method to copy data on same setTable.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$product = Product::find(2);

$newProduct = $product->replicate()->save();

dd($newProduct);

}

}

i hope it can help you...

Tags :
Shares