Laravel Move Data from One Table to Another Table Example

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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsUser;

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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsUser;

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.medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

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

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsProduct;

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…

Leave a Comment