In large scope projects, we use multiple data sources to control the flow of data and to manage it. Here, inside this article we will see the concept of working with multiple database connection in Laravel 8.
There are very few steps which is very very easy to do and connect with multi databases and perform operations. This is going to be very interesting article to learn and see the things. After this article two things will be totally clear out.
- Multiple databases
- Multiple connection groups
Let’s get started.
Laravel Installation
We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.
Here is the command to create a laravel project-
composer create-project --prefer-dist laravel/laravel blog
To start the development server of Laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Step #1 Update Env File
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
Step #2 Update Database File
Open database.php from /config folder. This file contains the information of connection groups. Now, we need to use .env variables (secondary database) into it.
<?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'), ]) : [], ], //... ], //... ];
Successfully, we have configured laravel 8 application with multiple database connections. Let’s see it’s usage.
Database Connections in Migration
When we create a migration file from artisan command, it stores at /database/migrations folder and connected with primary database..
To connect with multiple database to migrations, look here these examples.
Primary Database(Default)
<?php //... public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('description')->nullable(); $table->timestamps(); }); } //...
Secondary Database
To connect migration with second database, use only Schema::connection(‘mysql_2’). Use connection method and connection name in both up() and down() methods.
<?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(); }); } //...
Database Connections in Models
When we create models using artisan command, it will be stored at /app/Models and by default it will be connected to primary database.
To connect with multiple databases, look these examples.
Primary Database(Default)
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { //... }
Secondary Database
To use secondary database in model, use $connection protected variable in Model class.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model{ protected $connection = 'mysql_2'; }
Database Connections at Controller
If suppose, sometimes we want to connect database at runtime then we can connect direct from controller.
Primary Database(Default)
<?php //... class ProductController extends BaseController { public function getProducts() { $productModel = new Product; $find = $productModel->find(1); return $find; } }
Secondary Database
To connect with secondary database we use setConnection() method by model object and set connect group into it.
<?php //... class ProductController extends BaseController { public function getProducts() { $productModel = new Product; $productModel->setConnection('mysql_2'); $find = $productModel->find(1); return $find; } }
Database Connection with Query Builder
We will see connection of query builder with primary and secondary database.
Primary Database(Default)
$products = DB::table("products")->get(); print_r($products);
Secondary Database
$products = DB::connection('mysql_2')->table("products")->get(); print_r($products);
We hope this article helped you to learn about Working with Multiple Database Connection in Laravel 8 in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.