Logging Database Queries in Laravel
When developing Laravel applications, gaining insight into the database queries executed by your code can be invaluable for debugging and optimizing performance. In this post, we'll explore a simple yet effective method to log every database query during development using Laravel's service providers.
The Code
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Check if the application is running in the local environment
if (App::environment('local')) {
// Register a listener for database queries
DB::listen(function ($query) {
// Check if debugging is enabled
if (config('app.debug')) {
// Generate the SQL query string
$sql = Str::replaceArray('?', $query->bindings, $query->sql);
// Log the query to a specific channel named 'database'
\Log::channel('database')->debug($sql);
}
});
}
}
}
Explanation
-
Environment Check: The
AppServiceProvider
class'sboot()
method checks if the application is running in the local environment usingApp::environment('local')
. -
Database Query Listener: If the application is in the local environment, a listener for database queries is registered using
DB::listen()
. -
Debugging Check: Before logging each query, the code checks if debugging is enabled in the application's configuration using
config('app.debug')
. -
Logging Queries: The SQL query string is generated by replacing placeholders (
?
) with actual parameter values, and the resulting query is logged to a specific logging channel named'database'
.
This simple approach allows developers to log database queries effortlessly during development, providing valuable insights into the application's database interactions.
Stay tuned for our next post, where we'll explore more advanced tools for monitoring database queries in Laravel applications.
Top comments (2)
Very useful !
Note that you can also see all requests (along with the time taken) using Clockwork, which is my preferred way of doing it.
Thanks @nicolus for your valuable feedback I wrote about this in this dev.to/muhammadsaim/advanced-datab... post.