• Calculating...
  • 5 years ago
  • 9.4K Views
  • Archived This is an Archived post.
    The content within this may not be used or replaced with newer versions.

Connecting Multiple Databases in Laravel 5.8

This tutorial is created to implement multiple database connections using mysql. Let’s see how to configure multiple database connections in Laravel 5.8.

 

#Laravel 5.8

Laravel 5.8 continues the improvements made in the previous release (version 5.7). Refer release notes to see the changes made in Laravel 5.8.

  1. Install Laravel 5.8

First, let’s install Laravel 5.8 using the following command (Make sure to have composer installed in your PC) to Install Composer.

composer create-project --prefer-dist laravel/laravel multiDatabase

 
  1. Configure Database Details

You need to configure the databases at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql
DB_HOST='Your DB Host'
DB_PORT='Your DB Port'
DB_DATABASE='Your DB Name'
DB_USERNAME='Your DB UserName'
DB_PASSWORD='Your DB Password'

DB_CONNECTION_2=mysql
DB_HOST_2='Your DB Host'
DB_PORT_2='Your DB Port'
DB_DATABASE_2='Your DB Name'
DB_USERNAME_2='Your DB UserName'
DB_PASSWORD_2='Your DB Password'
 

In this step, Update “config/database.php” with following code to create database connections.

 

config/database.php

'default' => 'mysql',
'connections' => [

    '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_2'),
        'host' => env('DB_HOST_2'),
        'port' => env('DB_PORT_2'),
        'database' => env('DB_DATABASE_2'),
        'username' => env('DB_USERNAME_2'),
        'password' => env('DB_PASSWORD_2'),
       ....
    ]
]
 
  1. Create the migration file.

Go to the terminal and type the following php artisan command to generate the model and migration file.

 
php artisan make:migration create_multi_data_table
 

The migration will be created under “database/migrations”. Edit the file with the code below to Create Multi Data Table.

create_multi_data_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMultiDataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::connection('mysql2')->create('multiData', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
   Schema::connection('mysql2')->dropIfExists('multiData');
}
}
 

Type the following command to run the migration

php artisan migrate --database=mysql2
 
  1. Create Controller and model

If you encounter any errors, Clear the cache by running the following command.

php artisan config:cache
 

Create the multiData model using the following command.

php artisan make:model multiData
 

The model wil be generated in “app/multiData.php” Now, we will write the schema inside multiData.php file. Specify the “$connection” variable as shown below.

multiData.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class multiData extends Model
{
     protected $connection = 'mysql2';
}
 

Create the MultiDataController by typing the following command.

php artisan make:controller MultiDataController
 

app/Http/Controllers/MultiDataController.php

<?php
namespace App\Http\Controllers;

use App\Student;
use Illuminate\Http\Request;

class MultiDataController extends Controller
{

    public function yourMethod()
    {
        $multiData = new multiData;
        $multiData->setConnection('mysql2');
        $multi = $multiData->find(1);
        return $multi;
    }

}
 

You can also define custom connection with query builder as shown below

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

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Share:

Related Post

CRUD Operations In Laravel 8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 8. Laravel is one of the fastest-growing frameworks for PHP.

  • 3 years ago

Scheduling Tasks with Cron Job in Laravel 5.8

Cron Job is used to schedule tasks that will be executed every so often. Crontab is a file that contains a list of scripts, By editing the Crontab, You can run the scripts periodically.

  • 5 years ago

Integrating Google ReCaptcha in Laravel 5.8

reCAPTCHA is a free service from Google. It’s a CAPTCHA-like system designed to recognize that the user is human and, at the same time, assist in the digitization of books. It helps to protects your w

  • 5 years ago

Clearing Route, View, Config Cache in Laravel 5.8

Sometimes you may face an issue that the changes to the Laravel Project may not update on the web. This occures when the application is served by the cache. In this tutorial, You’ll learn to Clear App

  • 5 years ago

Import, Export from Excel to Database in Laravel 5.8, 5.7, 5

This tutorial is created to Import, Export data from an excel sheet to database in Laravel Framework using maatwebsite/excel package. It provides an easy way to import and export using database model.

  • 5 years ago