To determine which server was used for a read operation in a Laravel application that is configured with multiple read connections, you can listen for the Illuminate\Database\Events\QueryExecuted event and then log the connection name along with the query details. Here's how you can do it:
First, you need to create a listener for the QueryExecuted event. You can do this by running the following Artisan command:
php artisan make:listener LogDatabaseQuery --event=Illuminate\Database\Events\QueryExecuted
This will create a new listener class in your app/Listeners directory. Open the generated LogDatabaseQuery listener and modify the handle method to log the connection name and the query:
<?php
namespace App\Listeners;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;
class LogDatabaseQuery
{
/**
* Handle the event.
*
* @param \Illuminate\Database\Events\QueryExecuted $event
* @return void
*/
public function handle(QueryExecuted $event)
{
// Get the connection name
$connectionName = $event->connectionName;
// Log the connection name and the query
Log::info("Query executed on connection '{$connectionName}': {$event->sql}", [
'bindings' => $event->bindings,
'time' => $event->time,
]);
}
}
Next, you need to register the listener in your EventServiceProvider. Open the app/Providers/EventServiceProvider.php file and add the listener to the $listen array:
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Database\Events\QueryExecuted;
use App\Listeners\LogDatabaseQuery;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
QueryExecuted::class => [
LogDatabaseQuery::class,
],
];
// ...
}
Now, whenever a query is executed, Laravel will trigger the QueryExecuted event, and your listener will log the connection name and the query details.
Please note that logging every query can have a performance impact on your application, especially if you have a high number of queries being executed. It's recommended to use this approach only in a development environment or when debugging specific issues.