首页 > 解决方案 > How to use Multiple Databases based on subdomein in Laravel

问题描述

What I want, is to access a separate database, based on the subdomain. All other settings keep the same: username, password etc. Only database name needs to change.

I add This to database.php file

'subdomain' => [
            'driver' => 'mysql',
            'host' => '',
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

I also created Middleware

`$subdomain = $request->route()->account;

    $customer = Customer::where( 'sub_domain', $subdomain )->first();

    if( ! $customer ) {
        // account not found, do something else
    } else {
        Config::set('database.connections.subdomain.host', 'testdomain');
    }
    return $next($request);`

this is in route.php

Route::group(['domain' => $domain, 'middleware' => 'subdomain'],function () {});

Use protected $connection = 'subdomain'; in Model

in .env I use default database for check customer database name

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ispsoft
DB_USERNAME=root
DB_PASSWORD=

I got subdomain user database name. But not connected sudomain database And I did not get value from subdomain database

标签: laravelsubdomain

解决方案


尝试$table根据子域设置您的模型。如果它只是一个不同的 mysql 模式,你应该能够做这样的事情:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Widget extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    $subdomain = Config::get('database.connections.subdomain.host', 'testdomain');

    protected $table = $subdomian.'.widgets';
}

推荐阅读