How to Transfer Data between Tables in Laravel

How to Transfer Data between Tables in Laravel

Laravel provides a lot of features that make the development process easier, faster, and more efficient. One of the important features in Laravel is the ability to transfer data between tables. In this article, we'll show you how to transfer data between tables in Laravel.

Method 1: Move one record

In this method we will use replicate() and settable() method to move a record from one table to other.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class DataMover extends Controller
{
    public function index(Request $request)
    {
        $user = User::find(1);
        $user->replicate()
             ->setTable('inactive_users')
             ->save();
    }
}

Method 1: Move multiple records

In this method we will use replicate() and settable() method to move multiple records from one table to other.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class DataMover extends Controller
{
    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();
                  });
    }
}

Comments

No Comment posted Yet!

Leave a Reply

OK! You can skip this field.