动态更改Web路由的数据库连接Laravel

发布于 2025-02-02 02:34:01 字数 858 浏览 6 评论 0原文

我想动态更改数据库连接。我创建了用于更改数据库连接的中间件。它在API路线上起作用。但是它在网络路线上不起作用。

下面中间软件代码:

public function handle($request, Closure $next)
    {
        $cookie_name = 'x-connection-object';
        if(!empty($_COOKIE[$cookie_name])) {
            $connection = trim($_COOKIE[$cookie_name]);
            $db = strlen($connection) ? $connection : 'test213';
            \Config::set('database.default', 'mysql');
            $user = User::where('code', 'like', $db)->first();
            if($school) {
                \Config::set('database.default', $user->connection_name);
            } else {
                $error['institute_code'][]='Please Check Code';
                return response()->json(['errors'=>$error],422);
            }
        }
        return $next($request);
    }

我在运行时检查了数据库名称,显示了旧数据库名称,它没有显示新的数据库名称。

I want to change the database connection dynamically. I have created middleware for changing database connections. it works on API routes. But it does not work on the web routes.

below middleware code:

public function handle($request, Closure $next)
    {
        $cookie_name = 'x-connection-object';
        if(!empty($_COOKIE[$cookie_name])) {
            $connection = trim($_COOKIE[$cookie_name]);
            $db = strlen($connection) ? $connection : 'test213';
            \Config::set('database.default', 'mysql');
            $user = User::where('code', 'like', $db)->first();
            if($school) {
                \Config::set('database.default', $user->connection_name);
            } else {
                $error['institute_code'][]='Please Check Code';
                return response()->json(['errors'=>$error],422);
            }
        }
        return $next($request);
    }

I checked Database Name while running it shows the old database name it does not show the new database name.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少年亿悲伤 2025-02-09 02:34:01

在中间软件中使用以下代码

\Illuminate\Support\Facades\DB::setDefaultConnection('connection1');

和其他连接

\Illuminate\Support\Facades\DB::setDefaultConnection('connection2');

use below code in Middleware

\Illuminate\Support\Facades\DB::setDefaultConnection('connection1');

and for another connection

\Illuminate\Support\Facades\DB::setDefaultConnection('connection2');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文