How to use multiple databases in Laravel

Asked
Active3 hr before
Viewed126 times

8 Answers

multiple
90%

Using Multiple Database Connections,Multiple DB Connections in Laravel FROM fideloper.com,Connect multiple databases in laravel FROM tutsnare.com,When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

In .env

DB_CONNECTION = mysql
DB_HOST = 127.0 .0 .1
DB_PORT = 3306
DB_DATABASE = database1
DB_USERNAME = root
DB_PASSWORD = secret

DB_CONNECTION_SECOND = mysql
DB_HOST_SECOND = 127.0 .0 .1
DB_PORT_SECOND = 3306
DB_DATABASE_SECOND = database2
DB_USERNAME_SECOND = root
DB_PASSWORD_SECOND = secret

In config/database.php

'mysql' => [
   'driver' => env('DB_CONNECTION'),
   'host' => env('DB_HOST'),
   'port' => env('DB_PORT'),
   'database' => env('DB_DATABASE'),
   'username' => env('DB_USERNAME'),
   'password' => env('DB_PASSWORD'),
],

'mysql2' => [
   'driver' => env('DB_CONNECTION_SECOND'),
   'host' => env('DB_HOST_SECOND'),
   'port' => env('DB_PORT_SECOND'),
   'database' => env('DB_DATABASE_SECOND'),
   'username' => env('DB_USERNAME_SECOND'),
   'password' => env('DB_PASSWORD_SECOND'),
],

app/config/database.php

return array(

   'default' => 'mysql',

   'connections' => array(

      # Primary / Default database connection 'mysql' => array(
         'driver' => 'mysql',
         'host' => '127.0.0.1',
         'database' => 'database1',
         'username' => 'root',
         'password' => 'secret'
         'charset' => 'utf8',
         'collation' => 'utf8_unicode_ci',
         'prefix' => '',
      ),

      # Secondary database connection 'mysql2' => array(
         'driver' => 'mysql',
         'host' => '127.0.0.1',
         'database' => 'database2',
         'username' => 'root',
         'password' => 'secret'
         'charset' => 'utf8',
         'collation' => 'utf8_unicode_ci',
         'prefix' => '',
      ),
   ),
);

To specify which connection to use, simply run the connection() method

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

Query Builder

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

Set the $connection variable in your model

class SomeModel extends Eloquent {

   protected $connection = 'mysql2';

}

You can also define the connection at runtime via the setConnection method or the on static method:

class SomeController extends BaseController {

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

      $someModel - > setConnection('mysql2'); // non-static method

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

      $something = SomeModel::on('mysql2') - > find(1); // static method

      return $something;
   }

}

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

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

You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:

$pdo = DB::connection() - > getPdo();
load more v
88%

Using Multiple Database Connections, Database ,Connecting To The Database CLI,Running SQL Queries Using Multiple Database Connections Listening For Query Events

SQLite databases are contained within a single file on your filesystem. You can create a new SQLite database using the touch command in your terminal: touch database/database.sqlite. After the database has been created, you may easily configure your environment variables to point to this database by placing the absolute path to the database in the DB_DATABASE environment variable:

DB_CONNECTION = sqlite
DB_DATABASE = /absolute/path / to / database.sqlite
load more v
72%

Here is how to run more than one database connection.,You can also define the connection at runtime via the setConnection method.,Now that we have a 2nd database connection setup - how do we use it in code?,Similar to Schema Builder, you can define a connection on the Query Builder:

Inside of your datbase configuration file - likely app/config/database.php - you can define more than one database connection of any type. In fact, you can define as many connections as you'd like. For instance, if your application has to pull data from 2 MySQL databases, you can 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' => '',
      ),
   ),
);
load more v
65%

Database Connection with model,Database Connection with migration,Database Connection with Query Builder,Use Database Multiple Connection:

DB_CONNECTION = mysqlDB_HOST = 127.0 .0 .1 DB_PORT = 3306 DB_DATABASE = mydatabaseDB_USERNAME = rootDB_PASSWORD = root DB_CONNECTION_SECOND = mysqlDB_HOST_SECOND = 127.0 .0 .1 DB_PORT_SECOND = 3306 DB_DATABASE_SECOND = mydatabase2DB_USERNAME_SECOND = rootDB_PASSWORD_SECOND = root
load more v
75%

Having said that, let’s take a look at connecting and using multiple databases with Laravel.,store method not working in multiple database connections in laravel,As I said, Laravel allows you to connect multiple databases. We can use a different database platform like SQLite, MySQL, SQLSRV with Laravel. For this tutorial, I am going to use another MySQL instance of a separate database. In order words, we are going to deal with a separate MySQL database as additional storage., ask says: September 5, 2020 at 5:02 pmstore method not working in multiple database connections in laravelReply

config/database.php

< ? php

use Illuminate\ Support\ Str;

return [
      ...

      'connections' => [
         ...
         ...
         'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            '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,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
               PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
         ],

         'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST_2', '127.0.0.1'),
            'port' => env('DB_PORT_2', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME_2', 'forge'),
            'password' => env('DB_PASSWORD_2', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
               PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
         ],
      ]
load more v
40%

We hope this article helped you to learn about Working with Multiple Database Connection in Laravel 8 in a very detailed way.,CodeIgniter 4 Models with Multiple Database Connection,To connect with multiple database to migrations, look here these examples.,To connect with multiple databases, look these examples.

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel / installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel
$ laravel new blog

Here is the complete command to create a laravel project-

$ composer create - project--prefer - dist laravel / laravel blog
$ php artisan serve

Create secondary database environment variables. Open .env file and add details of other database as well.

# Primary Database

DB_CONNECTION = mysql
DB_HOST = 127.0 .0 .1
DB_PORT = 3306
DB_DATABASE = database_1
DB_USERNAME = root
DB_PASSWORD = root

# Secondary Database

DB_CONNECTION_2 = mysql
DB_HOST_2 = 127.0 .0 .1
DB_PORT_2 = 3306
DB_DATABASE_2 = database_2
DB_USERNAME_2 = root
DB_PASSWORD_2 = root
< ? php

use Illuminate\ Support\ Str;

return [

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

   'connections' => [

      //...

      // Primary database
      'mysql' => [
         'driver' => 'mysql',
         'url' => env('DATABASE_URL'),
         '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,
         'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
         ]) : [],
      ],

      // Secondary database
      'mysql_2' => [
         'driver' => 'mysql',
         'url' => env('DATABASE_URL'),
         'host' => env('DB_HOST_2', '127.0.0.1'),
         'port' => env('DB_PORT_2', '3306'),
         'database' => env('DB_DATABASE_2', 'forge'),
         'username' => env('DB_USERNAME_2', 'forge'),
         'password' => env('DB_PASSWORD_2', ''),
         'unix_socket' => env('DB_SOCKET', ''),
         'charset' => 'utf8mb4',
         'collation' => 'utf8mb4_unicode_ci',
         'prefix' => '',
         'prefix_indexes' => true,
         'strict' => true,
         'engine' => null,
         'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
         ]) : [],
      ],

      //...

   ],

   //...
];
< ? php

//...

public
function up()

{
   Schema::create('products', function(Blueprint $table) {

      $table - > increments('id');

      $table - > string('title');

      $table - > string('description') - > nullable();

      $table - > timestamps();

   });

}

//...
< ? php

//...

public
function up()

{
   Schema::connection('mysql_2') - > create('products', function(Blueprint $table) {

      $table - > increments('id');

      $table - > string('title');

      $table - > string('description') - > nullable();

      $table - > timestamps();

   });

}

//...
< ? php

namespace App;

use Illuminate\ Database\ Eloquent\ Model;

class Product extends Model {
   //...
}
< ? php

namespace App;

use Illuminate\ Database\ Eloquent\ Model;

class Product extends Model {

   protected $connection = 'mysql_2';

}
< ? php

//...
class ProductController extends BaseController {
   public
   function getProducts() {
      $productModel = new Product;

      $find = $productModel - > find(1);

      return $find;
   }
}
< ? php

//...

class ProductController extends BaseController {
   public
   function getProducts() {
      $productModel = new Product;

      $productModel - > setConnection('mysql_2');

      $find = $productModel - > find(1);

      return $find;
   }
}
$products = DB::table("products") - > get();

print_r($products);
$products = DB::connection('mysql_2') - > table("products") - > get();

print_r($products);
load more v
22%

In config/database.php Here we can see an array of all connections like MySQL, PostgreSQL, SQL Server. Here we can add more than one connection with the same database system.,So, we have a new connection named mysql_external which has the credentials provided, now time to use it. So in your code.,In this post, we will be using MySQL. So, let’s copy a default array item and paste as another one underneath – and call it mysql_external,Sometimes we need two or more databases for the same Laravel project, So we can easily connect our Laravel Application with external data from another database

config/database.php

'connections' => [

   'sqlite' => [
      // ...
   ],

   'mysql' => [
      'driver' => 'mysql',
      'host' => env('DB_HOST', 'localhost'),
      'database' => env('DB_DATABASE', 'forge'),
      'username' => env('DB_USERNAME', 'forge'),
      'password' => env('DB_PASSWORD', ''),
      'charset' => 'utf8',
      'collation' => 'utf8_unicode_ci',
      'prefix' => '',
      'strict' => false,
   ],

   'mysql_external' => [
      'driver' => 'mysql',
      'host' => env('DB_EXT_HOST', 'localhost'),
      'database' => env('DB_EXT_DATABASE', 'forge'),
      'username' => env('DB_EXT_USERNAME', 'forge'),
      'password' => env('DB_EXT_PASSWORD', ''),
      'charset' => 'utf8',
      'collation' => 'utf8_unicode_ci',
      'prefix' => '',
      'strict' => false,
   ],

   'pgsql' => [
      // ...
   ],

   'sqlsrv' => [
      // ...
   ],

],
load more v
60%

Step 2: Create Database,Step 1: Install Laravel,How to Use Multiple Database Connections in Laravel 8,Step 5: Create Dummy Data

Step 1: Install Laravel

//via Laravel Installer
composer global require laravel / installer
laravel new laravel - multiple - database

//via Composer
composer create - project laravel / laravel laravel - multiple - database
load more v

Other "multiple-undefined" queries related to "How to use multiple databases in Laravel"