Custom Laravel Database Connection

While working with the amazing package Tenancy which provides multi-tenancy support to Laravel, I ran into a problem with using Laravel Passport. The package works by setting up an individual database for each tenant that your application has. It makes this possible by overwriting the $connection property of Eloquent models.

Unfortunately, this task can prove to be difficult for third-party packages where you cannot extend the Eloquent models. This is very much the case for Laravel Passport.

Luckily, we have access to the TokenRepository class used by Laravel. An instance of this repository is bound to Laravel's IOC. This means that we have the freedom to overwrite this repository using Laravel's bind method on the container.

$this->app->bind(\Laravel\Passport\TokenRepository::class, \App\Support\Oauth\TokenRepository::class);

We are now free to overwrite any methods in the TokenRepository, including changing the database connection for the application and thus for Laravel Passport.

<?php

namespace App\Support\Oauth;

use Illuminate\Contracts\Foundation\Application;
use Laravel\Passport\TokenRepository as BaseTokenRepository;

class TokenRepository extends BaseTokenRepository
{
    public function __construct(Application $app)
    {
        $app['config']->set('database.default', $app['config']->get('tenancy.db.tenant-connection-name'));
    }
}

In theory, the database connection should only be changed for Laravel Passport when calling any of its controllers that use this TokenRepository, making it an ideal place to hook into. Any direct access of the Eloquent models in Laravel passport may always be extended when needed for your own purposes.

Overiding the connection for any third-party Eloquent models is also possible by using an observer and hooking into the events that models emit. You see an example at cc08069c639af9db686412f576163f268a4a8202.


Posted: Wednesday, April 18, 2018

Comments

Leave a Comment