How To Fetch Data From One Table And Insert Into Another Table In Laravel

In this tutorial, I will show you laravel move data from one table to another. From this example, you will learn a simple example of laravel migrate data from one table to another table. I want to share with you how to move data one table to another table in laravel. I will give you a complete example of how to migrate data one table to another table in laravel.

Laravel provides a replicate() eloquent method to copy records from one table to another table. To copy records, I will use the replicate() with setTable() method to migrate data from one table to another. I will give you the three examples for clearly understanding: We can easily use replicate() from laravel 9 version.

 

Example 1: Move One Row to Another Table in Laravel

Here, we will use the replicate() and setTable() methods to move one record to another table.

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: Move Multiple Rows to Another Table in Laravel

Here, we will use the replicate() and setTable() methods to move multiple records to another table.

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: Copy Data to the Same Table in Laravel

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

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 Customize Page Key Name in Laravel Pagination

 

Hope it can help you.

 

#laravel