Using Multiple Databases in Laravel 8
Tags: laravel, webdev, database, beginners
Published: 2022-03-03 10:10:53

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](https://laravel.com/docs/8.x/database), set [ENV Variables](https://laravel.com/docs/8.x/configuration#environment-configuration), create [Migrations](https://laravel.com/docs/8.x/migrations), [Eloquent Model](https://laravel.com/docs/8.x/eloquent), [Controller ](https://laravel.com/docs/8.x/controllers)and [Routes](https://laravel.com/docs/8.x/routing). Just follow the Steps given below.

**Note: **If you have not installed the Laravel 8 then read this tutorial [Install Laravel 8](https://www.w3courses.org/how-to-install-laravel-8/).

{% embed https://youtu.be/0C6aSVFc504 %}

## 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.

``` php
'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'),
            ]) : [],
        ],
```

## 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.
```php
#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=
```

## 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
<?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';
}
```
Again inside app\Models directory create a File Staff.php and paste the code given below.

```php
<?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';
}

```

In both the models Customer and Staff we have used the model properties [$table](https://laravel.com/docs/8.x/eloquent#table-names) to define table name and [$connection](https://laravel.com/docs/8.x/eloquent#database-connections) 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
<?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)
    {
        //
    }
}

```
In create method we have used the Customer Model to insert data in customers table. You can read about [database queries using Eloquent Model](https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models).

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

```php
<?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)
    {
        //
    }
}

```
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](https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models).

## Step 5 – Create Resource Route in Laravel 8
Inside the routes directory open web.php file and paste the code given below.
```php
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\StaffController;

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

Route::resource('staffs', StaffController::class);
```
**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](https://www.w3courses.org/tutorials/).

Thanks:)
Happy Coding:)