1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for your answer. It perfectly solved my problem. A big hug.
I used this solution to override PDO object creation since I need the connection string to declare itself as a dblib connection even though Laravel itself gives error when declaring "dblib" as connection drive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.