Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get data from another project database

I'm moving the old project database to a new project database. the structure of the old project database is a single MYSQL database and the new project is the multi-tenant database which contained a lot of subdomains. Also, the new project already set up a RESTFUL API to receive the data from the old project. Therefore, my idea is to implement the multi-connection in the new project in order to link both databases together then get data from the old project. Example, the new project sales table is an empty and old project sales table already contains some data. Now in my new project interface maybe have a sync button in order to move data from the old database into a new database. Do I need to pass the API key before sending data into a new project? Since it's a multi-tenant structure.

This is my config/database

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'aurora-2016-cluster.cluster-rtygfdfg.ap-southwest-1.rds.amazonaws.com',
            'database'  => 'newProject',
            'username'  => @$_ENV['DB_USER'] ?: '',
            'password'  => @$_ENV['DB_PASS'] ?: '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'oldProject',
            'username'  => 'root',
            'password'  => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
like image 589
soyacincau Avatar asked Feb 25 '26 01:02

soyacincau


1 Answers

Its Quite Simple in laravel open your config/databse.php file

you will find the code like this

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

];

Steps to be followed

Step1: Adding new arry to databse connection array

'mysqlSecondConnection' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST1', '127.0.0.1'),
            'port' => env('DB_PORT1', '3306'),
            'database' => env('DB_DATABASE2', 'secondDatabseName'),
            'username' => env('DB_USERNAME2', 'secondDatabseUserName'),
            'password' => env('DB_PASSWORD2', 'secondDatabsePassword'),
            'unix_socket' => env('DB_SOCKET2', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

After this your file may look like

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

        'mysqlSecondConnection' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST1', '127.0.0.1'),
            'port' => env('DB_PORT1', '3306'),
            'database' => env('DB_DATABASE2', 'secondDatabseName'),
            'username' => env('DB_USERNAME2', 'secondDatabseUserName'),
            'password' => env('DB_PASSWORD2', 'secondDatabsePassword'),
            'unix_socket' => env('DB_SOCKET2', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],


        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

];

Step2: Configure Your Database name in mysqlSecondConnection array

IF THIS PROJECT IS TEAM COLLABRATING DONT FORGET TO ADD THE NEW ATTRIBUTES IN .ENV FILE

Step 3: Now we are finished configuring the databse

Step 4: Open you Model that need to interacts with the mysqlSecondConnection Database

And add the

Property

protected $connection ='mysqlSecondConnection';

After this the mode may look like For Eg: I am Considering it as Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
/**
 * Class Cat
 *
 * @package App
*/

class Post extends Model
{


    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection ='mysqlSecondConnection';

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

     /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'posts';

    /**
     * The primary key for the model.
     *
     * @var string
     */

    protected $primaryKey = 'id';

    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'int';



    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name','title','desc'];

     /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [];

    /**
     * @var array
     */
    protected $dates = ['created_at','updated_at'];


}

Thats its

Now the testing part

Open your web.php file inside route folder

and paste the following code

Route::get('/testSecondConnection', function () 
{
    $posts= App\Post::all();
    dd($posts);

});

Now navigate to yourApplication/testSecondConnection

now see the connection property in the dumped

EDITED

I actually Forget to add another method that is via DB Facade version

Just pass the connection name to the DB inside the connection method

While using this this does not check for model

for the $connection Property in Post Model

$dbVersion = \DB::connection('mysqlSecondConnection')->table('posts')->get();
dd($dbVersion);

Edited for But which method is more efficient?

Good question Mate

Situation 1:

For Eg:

If You are Using the mysqlSecondConnection for the Post model in all the situation of your project then add this to Your model

protected $connection ='mysqlSecondConnection';

and this is good and NOTE $connection Property Will work on Eloquent not in DB Facade

Situation 2:

`Eg:'

if you are using only few Queries and calls to that mysqlSecondConnection

You Dont need to add

protected $connection ='mysqlSecondConnection';

Post Model

DB Facade Version 

$dbVersion = \DB::connection('mysqlSecondConnection')->table('posts')->get();
    dd($dbVersion);

Eloquent Version

$eloquentVersion = Post::on('mysqlSecondConnection')->get()
    dd($eloquentVersion);

YOU MAY GET THE DOUBT WHY DB FACADE IS NOT USING mysqlSecondConnection IN POST MODEL

Solution:

While using the DB FACADE

It Will look into the config/datbase.php

for default array

Which is used in connection to database

'default' => env('DB_CONNECTION', 'mysql'),

Hope its helps and look clear

like image 83
ManojKiran Appathurai Avatar answered Mar 01 '26 02:03

ManojKiran Appathurai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!