You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.5如何获取当前读写查询对应的DB_HOST值

验证Laravel 5.5读写分离的数据库连接Host

Hey there! Since you've already set up read-write separation in your Laravel 5.5 project, let's go through a couple of practical ways to confirm which DB hosts are being used for read and write queries.

方法1:直接获取连接实例的Host信息(快速测试)

This is the simplest way to check immediately—you can run this code in a controller, route closure, or even Artisan tinker:

验证写连接Host

// 获取默认的写连接实例
$writePdo = DB::connection()->getPdo();
// 输出写连接的Host
echo "Write Connection Host: " . $writePdo->getAttribute(PDO::ATTR_HOST);

验证读连接Host

// 获取读连接实例
$readPdo = DB::connection('mysql')->getReadPdo();
// 输出读连接的Host
echo "Read Connection Host: " . $readPdo->getAttribute(PDO::ATTR_HOST);

说明:Laravel的getReadPdo()方法会直接指向你配置的read节点,而默认的getPdo()对应write节点的连接。

方法2:监听查询事件,追踪所有请求的连接信息(生产/实际场景)

If you want to verify the connection Host for every query in your app (like during actual user requests), you can register a query listener in your AppServiceProvider:

  1. Open app/Providers/AppServiceProvider.php and update the boot() method:
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Events\QueryExecuted;
use PDO;

public function boot()
{
    DB::listen(function (QueryExecuted $query) {
        // 判断当前连接是读还是写
        $isReadConnection = $query->connection->getReadPdo() === $query->connection->getPdo();
        $connectionType = $isReadConnection ? 'Read' : 'Write';
        
        // 获取当前连接的Host
        $host = $query->connection->getPdo()->getAttribute(PDO::ATTR_HOST);
        
        // 记录到日志(也可以输出到控制台)
        \Log::info("[{$connectionType}] Query Host: {$host} | SQL: {$query->sql}");
    });
}
  1. Now run some read/write operations in your app:

    • Read example: \App\User::all();
    • Write example: \App\User::create(['name' => 'Test User', 'email' => 'test@example.com']);
  2. Check the log file at storage/logs/laravel.log—you'll see entries like this:

[2024-05-20 12:34:56] local.INFO: [Read] Query Host: 127.0.0.2 | SQL: select * from `users`  
[2024-05-20 12:35:01] local.INFO: [Write] Query Host: 127.0.0.1 | SQL: insert into `users` (`name`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?)  

额外注意事项

  • If you have multiple read nodes configured, Laravel will randomly select one each time (for load balancing). Since you only have one read node, you'll consistently get 127.0.0.2 for read queries.
  • Make sure your .env file's DB_HOST_READ and DB_HOST_WRITE values are correctly loaded—you can verify this with php artisan config:cache (but remember to clear cache after changing .env).

内容的提问来源于stack exchange,提问作者Subhajit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:14