DEV Community

Cover image for Using Multiple Databases in Laravel 8
Chetan Rohilla
Chetan Rohilla

Posted on • Originally published at readymadecode.com

Using Multiple Databases in Laravel 8

Laravel 8 has many options to use different types of databases. For example, we can use SQLite, MYSQL, PostgreSQL, SQL Server, Laravel-OCI8 for Oracle Database. Sometimes, to Speed Up Our Application or Simplify Our Large-Database Application we needs to use Multiple Database for our Single Laravel Application. So, Here in this tutorial we will learn Laravel 8 Multiple Database and Resource Routes with Controllers.

To use the Multiple Database in Laravel, we needs to create Database Configuration, set ENV Variables, create Migrations, Eloquent Model, Controller and Routes. Just follow the Steps given below.

**Note: **If you have not installed the Laravel 8 then read this tutorial Install Laravel 8.

Step 1 – Create Configuration For Database in Laravel 8

Here we will create the config for MYSQL Database. You need to open the database.php file in config directory. Inside the connections array there is a mysql key by default for first database. You just need to create one more key mysql2 for second database and paste the code given below.

'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST2', '127.0.0.1'),
            'port' => env('DB_PORT2', '3306'),
            'database' => env('DB_DATABASE2', 'forge'),
            'username' => env('DB_USERNAME2', 'forge'),
            'password' => env('DB_PASSWORD2', ''),
            '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'),
            ]) : [],
        ],
Enter fullscreen mode Exit fullscreen mode

Step 2 – Set Environment Variables in Laravel 8

Open .env file and set the database credentials as given below in code. Remember, DB_HOST2, DB_PORT2, DB_DATABASE2, DB_USERNAME2, DB_PASSWORD2 is for second database.

#First Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb1
DB_USERNAME=root
DB_PASSWORD=

#Second Database
DB_HOST2=127.0.0.1
DB_PORT2=3306
DB_DATABASE2=laraveldb2
DB_USERNAME2=root
DB_PASSWORD2=
Enter fullscreen mode Exit fullscreen mode

Step 3 – Create Eloquent Model in Laravel 8

Before creating the models we will create two sample database tables.

In Database(laraveldb1) Create a table(Customers) with fields – id, customer_name, customer_email, created_at, updated_at, deleted_at.

In Database(laraveldb2) Create a table(Staff) with fields – id, staff_name, staff_email, created_at, updated_at, deleted_at.

Inside app\Models directory create a File Customer.php and paste the code given below.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    use HasFactory;

    protected $table = 'customers';

    protected $connection = 'mysql';
}
Enter fullscreen mode Exit fullscreen mode

Again inside app\Models directory create a File Staff.php and paste the code given below.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Staff extends Model
{
    use HasFactory;

    protected $table = 'staff';

    protected $connection = 'mysql2';
}

Enter fullscreen mode Exit fullscreen mode

In both the models Customer and Staff we have used the model properties $table to define table name and $connection to define the connection we have created in Step 1.

Step 4 – Create Controllers in Laravel 8

First, inside the app\Http\Controllers directory create a file CustomerController.php and paste the code given below.

<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $customer = new Customer;
        $customer->customer_name = 'Customer 1';
        $customer->customer_email = 'customer1@example.com';

        if ($customer->save()) {
            return response()->json(['message' => 'Customer Added.']);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function show(Customer $customer)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function edit(Customer $customer)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Customer $customer)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Customer $customer)
    {
        //
    }
}

Enter fullscreen mode Exit fullscreen mode

In create method we have used the Customer Model to insert data in customers table. You can read about database queries using Eloquent Model.

Now, inside the app\Http\Controllers directory create a file StaffController.php and paste the code given below.

<?php

namespace App\Http\Controllers;

use App\Models\Staff;
use Illuminate\Http\Request;

class StaffController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $staff = new Staff;

        $staff->staff_name = 'Staff 1';
        $staff->staff_email = 'staff1@example.com';
        if ($staff->save()) {
            return response()->json(['message' => 'Staff Added']);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Staff  $staff
     * @return \Illuminate\Http\Response
     */
    public function show(Staff $staff)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Staff  $staff
     * @return \Illuminate\Http\Response
     */
    public function edit(Staff $staff)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Staff  $staff
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Staff $staff)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Staff  $staff
     * @return \Illuminate\Http\Response
     */
    public function destroy(Staff $staff)
    {
        //
    }
}

Enter fullscreen mode Exit fullscreen mode

Same, In create method we have used the Staff Model to insert data in staff table. You can also read about database queries using Eloquent Model.

Step 5 – Create Resource Route in Laravel 8

Inside the routes directory open web.php file and paste the code given below.

use App\Http\Controllers\CustomerController;
use App\Http\Controllers\StaffController;

Route::resource('customers', CustomerController::class);

Route::resource('staffs', StaffController::class);
Enter fullscreen mode Exit fullscreen mode

You can now use Multiple Databases in your any Laravel Applications. You can also now speed up and simplify your Laravel Application using Laravel 8 Multiple Database and Resource Routes with Controllers.


Please Like, Share and give positive feedback to motivate me to write more.

For more tutorials visit my website.

Thanks:)
Happy Coding:)

Discussion (0)