Laravel 5.5如何获取当前读写查询对应的DB_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:
- Open
app/Providers/AppServiceProvider.phpand update theboot()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}"); }); }
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']);
- Read example:
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.2for read queries. - Make sure your
.envfile'sDB_HOST_READandDB_HOST_WRITEvalues are correctly loaded—you can verify this withphp artisan config:cache(but remember to clear cache after changing.env).
内容的提问来源于stack exchange,提问作者Subhajit

