Why getQueryLog() Might Seem Broken and How to Fix It
When you need to inspect the raw SQL Eloquent generates, it is common to encounter a confusing situation where getQueryLog() appears to return an empty array or fails entirely. The snippet you provided demonstrates a specific implementation flaw: calling $order->all() immediately before attempting to log the query. In that context, $order is likely an instance of the model representing a single entity, not a collection builder.
Calling methods like all(), first(), or even accessing properties on a model instance often triggers hydration, which consumes the underlying query builder state or executes the logic before you have a chance to capture the specific SQL intended for that operation. If $order is a single model instance retrieved from the database, calling $order->all() will effectively throw an exception because you cannot call all() on an already hydrated entity.
The core issue lies in understanding what Eloquent stores and when it exposes it. The query log is not a static property attached to every model; it is managed by the database connection instance associated with that specific request context. To retrieve the logs successfully, you must access them through the database connection itself, or ensure you are inspecting the builder object used for the operation before hydration occurs.
Accessing the Query Log via the Connection
The most reliable method to inspect query logs in Laravel is by accessing the getQueryLog() method directly on the database connection instance. This approach bypasses any ambiguity regarding model instances and captures all queries executed during the current request lifecycle.
You can retrieve the log using the following pattern:
use Illuminate\Support\Facades\DB;
public function show(Order $order) {
$log = DB::connection()->getQueryLog();
// Optional: Format output for readability if needed
foreach ($log as $query) {
dd($query);
}
}
In this example, DB::connection() returns the active connection for the current application environment (e.g., SQLite, MySQL, PostgreSQL). Calling getQueryLog() on this connection returns an array containing all queries that have been executed since the connection was established or reset. Each entry in the array typically includes the raw SQL string, bindings, and time taken to execute.
Debug Mode Dependency
It is crucial to understand that getQueryLog() only returns data when debug mode is enabled. If your application is running with APP_DEBUG set to false, the query log will be empty even if queries were executed. This is a security feature designed to prevent sensitive information leakage in production environments.
To ensure you can see the logs during development or local testing, verify your .env file:
APP_DEBUG=true
If you are running a long-lived process like a queue worker or a scheduled task, the query log might persist across multiple jobs if not managed correctly. In such cases, it is often better to enable logging explicitly for that specific request scope or clear the log after inspection to keep memory usage under control.
Using --query with Artisan Commands
If your goal is to inspect queries without writing custom code, you can leverage Artisan commands. When running migrations or other database interactions via the CLI, Laravel provides a convenient flag to print query logs directly to the console:
php artisan migrate --force --query
This option is particularly useful when troubleshooting migration scripts that seem to hang or fail silently. It outputs each SQL statement along with its execution time and bindings, giving immediate insight into what the framework is doing under the hood.
Best Practices for Production
While inspecting query logs is invaluable for debugging, you should never enable APP_DEBUG=true in a production environment. Additionally, relying on the global query log can impact performance if left active for long-running processes. If you need to monitor queries in production without exposing them via the log array, consider using database-specific profiling tools or integrating with external APM solutions that capture SQL metrics without polluting your application memory.
By accessing the connection's query log directly and ensuring debug mode is active, you can effectively diagnose performance bottlenecks and understand how Eloquent translates your models into SQL statements.