Home > Back-end >  Laravel - How to set additional parameters in database connection string?
Laravel - How to set additional parameters in database connection string?

Time:05-25

I'm currently migrating a legacy system to laravel and I'm facing an issue regarding using additional parameters while connecting to the database.

Below is the current code:

try {
    $dns = "pgsql:host=<HOST>;port=<NUMBER_PORT>;dbname=<DB_NAME>";
    $options = [PDO::ATTR_PERSISTENT => true];
    $this->driver = new PDO($dns, <DB_USERNAME>, <DB_PASSWORD>, $options);
    
    $this->driver->query("SET app.current_tenant = {<TENANT_ID>}");
    $this->driver->query("SET app.current_institution = {<INSTITUTION_ID>}");

    $this->driver->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage();
}

My question is: how to set the app.current_tenant and app.current_institution parameters when connecting to the database in Laravel.

CodePudding user response:

One way to do this is to implement your own database connection class, overriding the connect() method to do what you want. At a very basic level, this could look like this:

app/Database/PostgresConnector.php

<?php

namespace App\Database;

use Illuminate\Database\Connectors\PostgresConnector as BaseConnector;

class PostgresConnector extends BaseConnector
{
    public function connect(array $config)
    {
        $pdo = parent::connect($config);
        $pdo->query("SET app.current_tenant = {<TENANT_ID>}");
        $pdo->query("SET app.current_institution = {<INSTITUTION_ID>}");

        return $pdo;
    }
}

Then you can write a service provider to use your custom connector instead of the default. app/Providers/DatabaseConnectorProvider.php

<?php

namespace App\Providers;

use App\Database\PostgresConnector;
use Illuminate\Support\ServiceProvider;

class DatabaseConnectorProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('db.connector.pgsql', PostgresConnector::class);
    }
}

Finally, ensure your service provider is being loaded in the providers array of config/app.php.

  • Related