PHP - How to configure . env from Laravel to access different databases and different languages?

Asked

Viewed 5,339 times

2

I am working on a system (portal) that offers service to 19 countries. For each country there is a database and each country with its language dictionary (even countries with the same language, have EX dictionaries: mexico and Spanha). The system was built in PHP, IIS windows 7. I want to migrate the system to php - Windows, apache, Linux. The first challenge I’m finding is the aqruivo . ENV configuration of the Laravel (latest version). It accepts a language and a database.

Enntão the logic is the following: when the user writes br.portal.mycompany.com the system must recover the credentials of access to the br_portal database and tbm recover the Labels in English (br) in the dictionary database.

How could you set up env to accept different credentials for different databases and different languages, based on different url possibilities ? Ex: br.portal.mycompany.com, us.portal.mycompany.com, es.portal.mycompany.com, etc....

1 answer

3


You can create different connections.

In the config/Databases.php file there is the connection of your default database, but Voce can create other connections. So:

'connections' => [

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'mysql2' => [ // Aqui você define o nome da conexão
            'driver' => 'mysql',
            'host' => env('DB_BR_HOST', 'localhost'),
            'port' => env('DB_BR_PORT', '3306'),
            'database' => env('DB_BR_DATABASE', 'forge'),
            'username' => env('DB_BR_USERNAME', 'forge'),
            'password' => env('DB_BR_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

    ],

Then in the file . env you put the data to the access. So:

DB_CONNECTION=mysql // Banco padrão
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME=root
DB_PASSWORD=


DB_BR_CONNECTION=mysql // Outros bancos
DB_BR_HOST=localhost
DB_BR_PORT=3306
DB_BR_DATABASE=database
DB_BR_USERNAME=root
DB_BR_PASSWORD=

And to make a query in the database you need to define which connection the application should use. So:

$sql = DB::connection('name_connection')->table('name_table')->get();

Browser other questions tagged

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