Home Laravel How To Move Data from One Table to Another Table In Laravel?

How To Move Data from One Table to Another Table In Laravel?

by Shahriar Sagor

Hello Dev’s today now in this tutorial i will shows you laravel move data from one table to another table. Here in this post i will give you a very simple example of laravel migrate data from one table to another table. So I would like to share with you an example how to move data one table to another table in laravel application. We will learn from here how to migrate data one table to another table in laravel.

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

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

Example 1: Laravel Move One Row to Another Table

Here, i 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, i will use replicate() and the setTable() method to move multiple records to the 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, i will be use replicate() and save() method to copy data on same as 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);
    }
}

Read Also: How To Use JQuery Ajax Loading Spinner In Laravel ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like