Laravel

Laravel TutorialChange default routing behaviour in Laravel 5.2.31 +CustomException class in LaravelDeploy Laravel 5 App on Shared Hosting on Linux ServerLaravel ArtisanLaravel AuthenticationLaravel AuthorizationLaravel Blade TemplatesLaravel CashierLaravel CollectionsLaravel Common Issues & Quick FixesLaravel ConstantsLaravel ControllersLaravel Cron basicsLaravel Cross Domain RequestLaravel Custom Helper functionLaravel DatabaseLaravel Database MigrationsLaravel Database SeedingLaravel Directory StructureLaravel DockerLaravel EloquentLaravel Eloquent : RelationshipLaravel Eloquent: Accessors & MutatorsLaravel Eloquent: ModelLaravel Error HandlingLaravel Events and ListenersLaravel Filesystem / Cloud StorageLaravel Form Request(s)Laravel Getting started with laravel-5.3Laravel HelpersLaravel HTML and Form BuilderLaravel InstallationLaravel Installation GuideLaravel Introduction to laravel-5.2Laravel Introduction to laravel-5.3Laravel lumen frameworkLaravel Macros in Eloquent RelationshipLaravel MailLaravel MiddlewareLaravel ObserverLaravel PackagesLaravel PaginationLaravel Permissions for storageLaravel PoliciesLaravel QueuesLaravel RequestsLaravel Route Model BindingLaravel RoutingLaravel SeedingLaravel ServicesLaravel SocialiteLaravel Task SchedulingLaravel TestingLaravel Token Mismatch Error in AJAXLaravel use fields aliases in EloquentLaravel Useful linksLaravel ValetLaravel ValidationMultiple DB Connections in LaravelNaming Files when uploading with Laravel on WindowsRemove public from URL in laravelSparkpost integration with Laravel 5.4



Multiple DB Connections in Laravel

From WikiOD

Initial Steps[edit | edit source]

Multiple database connections, of any type, can be defined inside the database configuration file (likely app/config/database.php). For instance, to pull data from 2 MySQL databases define them both separately:

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

The default connection is still set to mysql. This means unless otherwise specified, the application uses the mysql connection.

Using Eloquent[edit | edit source]

There are multiple ways to define which connection to use in the Eloquent models. One way is to set the $connection variable in the model:

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

The connection can also be defined at runtime via the setConnection method.

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

        $something = $someModel->find(1);

        return $something;
    }
}

Using Schema builder[edit | edit source]

Within the Schema Builder, use the Schema facade with any connection. Run the connection() method to specify which connection to use:

Schema::connection('mysql2')*>create('some_table', function($table)
{
    $table->increments('id'):
});

Using DB query builder[edit | edit source]

Similar to Schema Builder, define a connection on the Query Builder:

$users = DB::connection('mysql2')->select(...);

From Laravel Documentation[edit | edit source]

Each individual connection can be accessed via the connection method on the DB facade, even when there are multiple connections defined. The name passed to the connection method should correspond to one of the connections listed in the config/database.php configuration file:

$users = DB::connection('foo')->select(...);

The raw can also be accessed, underlying PDO instance using the getPdo method on a connection instance:

$pdo = DB::connection()->getPdo();

https://laravel.com/docs/5.4/database#using-multiple-database-connections

Credit:Stack_Overflow_Documentation