Thursday, December 26, 2024
Google search engine
HomeLanguagesLaravel Insert data from one table to another

Laravel Insert data from one table to another

Insert data from one table to another in Laravel; In this tutorial, you will learn how to insert data from one table to another table in laravel.

Laravel provides replicate() eloquent method to move or copy records from one table to another table. we will use replicate() with setTable() method to migrate data one table to another.

Copy and Insert data from one table to another Laravel

Here, you can see different example to copy and insert/move data from one table to another table in laravel; is as follows:

  • Ex 1: Laravel Move One Row to Another Table
  • Ex 2: Laravel Move Multiple Row to Another Table
  • Ex 3: Laravel Copy Data to Same Table

Ex 1: Laravel Move One Row to Another Table

In this example, you will see how to 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();
    }
}

Ex 2: Laravel Move Multiple Row to Another Table

In this example, you will see how to 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::select("*")
                ->where('last_login','<', now()->subYear())
                ->each(function ($user) {
                        $newUser = $user->replicate();
                        $newUser->setTable('inactive_users');
                        $newUser->save();
  
                        $user->delete();
                  });
    }
}

Ex 3: Laravel Copy Data to Same Table

In this example, you will see how to 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);
    }
}

Conclusion

That’s it; In this tutorial, you have learned how to insert data from one table to another table in laravel.

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments