Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nicknds97's avatar

Not able to extend DatabaseManager

I need to extend DatabaseManager to register a new connection as stated in API documentation, https://laravel.com/api/10.x/Illuminate/Database/DatabaseManager.html#method_extend

I am using code:

`app('db')->extend($connectioName, function ($config, $name) use ($databaseName) {
  Log::info("set database connecttion");
  $config['database'] = $databaseName;
});`

I am not able to see any Log message. I have checked using different ways but I am sure, the closure defined is not being executed. I am not able to identify the problem. Need help.

0 likes
2 replies
LaryAI's avatar
Level 58

The issue might be that the extend method is not being called at the right time. Try calling it in a service provider's boot method instead of directly in your code. Here's an example:

  1. Create a new service provider by running the following command:
php artisan make:provider DatabaseServiceProvider
  1. Open the newly created DatabaseServiceProvider and add the following code to the boot method:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class DatabaseServiceProvider extends ServiceProvider
{
    public function boot()
    {
        DB::extend('connection-name', function ($config, $name) {
            $config['database'] = 'new-database-name';
            return new \Illuminate\Database\MySqlConnection($config, $name);
        });
    }
}
  1. Register the service provider in config/app.php:
'providers' => [
    // ...
    App\Providers\DatabaseServiceProvider::class,
],
  1. Run your application and check the logs to see if the message is being logged.
nicknds97's avatar

@LaryAI I tried calling that function from ServiceProvider. Same result. I cannot execute the closure. Also, I need to set connections on demand, in a middleware.

Please or to participate in this conversation.