You can install the package via composer:
composer require usmonaliyev/laravel-db-connection-resolver
You can publish the config and migration files with:
php artisan vendor:publish --provider="Usmonaliyev\DbConnectionResolver\DbConnectionResolverServiceProvider"
You can run migrations with:
php artisan migrate
Add database connection to your config/database.php
:
'connections' => [
...
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...
],
'foo' => [
...
],
'bar' => [
...
]
]
You need to implement resolveConnectionName
function into your app/Models/User.php
file.
Or add Usmonaliyev\DbConnectionResolver\Traits\ConnectionResolver
trait your User class.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Usmonaliyev\DbConnectionResolver\Traits\ConnectionResolver;
class User extends Authenticatable
{
use ConnectionResolver, HasFactory, HasApiTokens;
...
To resolve database connection while accepting request, assign middleware to your routes.
use Usmonaliyev\DbConnectionResolver\Middleware\ConnectionResolverMiddleware;
Route::middleware([ConnectionResolverMiddleware::class])->group(function () {
Route::get('/', function () {
//
});
});
Assigning middleware to routes
The MIT License (MIT).