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 install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven't installed Composer on your PC.

    composer create-project --prefer-dist laravel/laravel multiDatabase
  2. 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'),
           ....
        ]
    ]
    
    
  3. 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
  4. 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.