LARAVEL

How to Transfer Data between Tables in Laravel

How-to-Transfer-Data-between-Tables-in-Laravel.png

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();
                  });
    }
}



About author

IMG_8897.png

Muhammad Zubair

My name is Muhammad Zubair. I'm a full-stack developer. I'm a owner of theskillstock.com. I love to write tutorials of PHP, Laravel, Html & css, Javascript, Java and much more with examples.


Comments

Hello World! https://apel.top/go/gu4winrshe5dgoju?hs=47f264a75166402f1fbb6d9e1dcb2334& Mar 24th 2023

zax1i4



Leave a Reply