简体   繁体   English

Laravel - 使用 Auth::user() 设置模型连接

[英]Laravel - Set model connection with Auth::user()

In my project every user has his/her database and I have defined the connection on config/database.php.在我的项目中,每个用户都有他/她的数据库,我在 config/database.php 上定义了连接。 So, in the model need to set the database connection.所以,在模型中需要设置数据库连接。

// defines default database connection
protected $connection = Auth::user()->database;

I can't use this because it will throw an error: Constant expression contains invalid operations我不能使用它,因为它会抛出一个错误:常量表达式包含无效操作

Can anyone help me with this please?任何人都可以帮我解决这个问题吗?

To store and show data, I use:为了存储和显示数据,我使用:

DB::connection(Auth::user()->database)->table(...

And works like a charm.并且像魅力一样工作。 Can someone help me with $connection to be ble to set it by a variable?有人可以用 $connection 帮助我通过变量设置它吗?

Regards问候

Solved the problem via middleware.通过中间件解决了问题。

public function handle($request, Closure $next, $database)
{
    // check witch database connection to use
    switch ($database) {
        case 'self':
            // Set the User Database Connection
            DB::setDefaultConnection(Auth::user()->database);
            // Reconnect
            DB::reconnect();
            break;
        case 'main_db':
            // Set the User Database Connection
            DB::setDefaultConnection('main_db');
            // Reconnect
            DB::reconnect();
            break;
        default:
            // default action
            abort(403, 'Não está autorizado a aceder ao recurso solicitado.');
            break;
    }
    // next request...
    return $next($request);
}

And, in every controller:而且,在每个控制器中:

public function __construct()
{
    // calls the middleware: SetDatabaseConnection
    $this->middleware('SetDatabaseConnection:self');
}

Thanks for the tips.谢谢你的提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM