Laravel 5 - How to connect multiple Bases at the same time?

Asked

Viewed 1,366 times

4

I’ve researched several places, and they all end up leading to that link. But I could not work using the methods given in the link.

The problem: I have 3 banks configured in config/database.php: "main", "bank-1" and "financial", and I need to use all 3 in the same controller. The system only accesses one of them, the other 2 only serve for validations at login time, such as financial check and others.

I receive 3 values per POST: "company", "login" and "password". I create a variable $empresa, which is first used in the bank banco-1. Validations made, the same variable needs to be checked in the bank financeiro. After a positive return, then I access the system bank and check the login and password.

class LoginController extends Controller
{
  public function entrar(Request $request){
    $usuario = new \App\usuario();

$login = $request->usuario;
$senha = $request->senha;
$empresa = $request->empresa;
$cliente = DB::connection('banco-1')
->table('clientes')
->select('endereco','banco','nomecompleto','empresa','codigo','cnpj')
->where('empresa', '=',$empresa)->get();

Where $cliente is not a model, it is just a variable. Laravel returns the error saying that the table "clients" does not exist in the "main" bank, ie the DB::connection('banco-1') did not connect in the database-1 but in the main, and still the query ran.

It also follows how the config/database.php file is (the sensitive data removed, of course):

'default' => env('DB_CONNECTION', '-'),

'connections' => [

    'principal' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', '-'),
        'username' => env('DB_USERNAME', '-'),
        'password' => env('DB_PASSWORD', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'banco-1' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', '-'),
        'username' => env('DB_USERNAME', '-'),
        'password' => env('DB_PASSWORD', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'financeiro' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', '-'),
        'username' => env('DB_USERNAME', '-'),
        'password' => env('DB_PASSWORD', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
]

I am forgetting something?

  • Post the connection configuration file, I think I know what it is!

  • 1

    If nothing else works, and you only need to access these two banks in this single place, you could use the same PDO (or a preferred bank connector) in these two queries. At least until you can figure it out by Laravel himself.

  • @Virgilionovic I edited for you to take a look. Daniel thanks for the tip, I’ll do just that. But I wanted to make it work properly because I need this same scheme working on other systems.

  • @Cleitonoliveira was made an answer, you were using wrong, is because of this, something else in Eloquent itself can change to be easier, avoid using this in Controller, only in the last case even ... The answer explains how to solve.

1 answer

3


You are using it wrong so the configuration is the same in the 3 connections, where the helper (function) env is searching in the same key the database settings, user and password.

Corrections:

Filing cabinet config/database.php

Was added in the banco-1 with the settings of .env number 1 in front of configuration, example:

'database' => env('DB_DATABASE1', '-'),
'username' => env('DB_USERNAME1', '-'),
'password' => env('DB_PASSWORD1', '-'),

Also in the financeiro with the settings of .env number 2 in front of configuration, example:

'database' => env('DB_DATABASE2', '-'),
'username' => env('DB_USERNAME2', '-'),
'password' => env('DB_PASSWORD2', '-'),

Complete file:


'default' => env('DB_CONNECTION', '-'),

'connections' => [

    'principal' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', '-'),
        'username' => env('DB_USERNAME', '-'),
        'password' => env('DB_PASSWORD', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'banco-1' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE1', '-'),
        'username' => env('DB_USERNAME1', '-'),
        'password' => env('DB_PASSWORD1', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'financeiro' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE2', '-'),
        'username' => env('DB_USERNAME2', '-'),
        'password' => env('DB_PASSWORD2', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
]

Observing: where is the - (trait), is the default configuration value that will only be used if the first configuration value is not found.

In the archive .env that is at the root of your project add these settings as example below:

APP_ENV=local
APP_KEY=base64:xwuxK/b2WGIUpNb73qJgbF8H3T94YqH6aDBldhECSiw=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=root
DB_PASSWORD=senha

DB_DATABASE1=nome_do_banco
DB_USERNAME1=nome_do_usuario
DB_PASSWORD1=senha_do_banco

DB_DATABASE2=nome_do_banco
DB_USERNAME2=nome_do_usuario
DB_PASSWORD2=senha_do_banco
    
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

of course you will fill the values with the respective connection settings of your bank, exactly where they are bankname, username and password.


Direct way:

Change the values without the helper .env:

'default' => env('DB_CONNECTION', '-'),

'connections' => [

    'principal' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', '-'),
        'username' => env('DB_USERNAME', '-'),
        'password' => env('DB_PASSWORD', '-'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'banco-1' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => 'nome_do_banco',
        'username' => 'nome_do_usuario',
        'password' => 'senha_do_banco',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'financeiro' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '-'),
        'port' => env('DB_PORT', '3306'),
        'database' => 'nome_do_banco',
        'username' => 'nome_do_usuario',
        'password' => 'senha_do_banco',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
]

note that now the setting is direct on config/database.php without using the function env. Just change the values where you are 'database name', 'user name' and 'database password' in the two settings created.

Remembering that I only stipulated 3 settings nothing prevents it to be done in all two ways.

I prefer the first one, it takes a little work, but, I believe it stays in a suitable place and created by for loading such type settings.

References:

  • 1

    You were right, that’s right, thank you!

  • What it would look like for 100 customers ?

  • @Mikeotharan would be 100 settings. Although not having the explicit context basically is this.

  • But it is correct to do this ? There is no other method ? Because if my company reaches 10000 customers the code will be heavy.

  • 1

    @Mikeotharan your comment should be asked a question by placing all relevant points for an infinite increase of settings. In comments I would say that it lacks a context, lack your explanation for an increase of the type that is clearly unviable, so ask a well explained question of what you want to do.

  • I even asked a question about this here: https://stackoverflow.com/questions/56536223/one-database-or-several

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.