In this article, we will discuss “How to Log All SQL Queries in Laravel”, Log SQL query in laravel or check last execute sql query in laravel. As we know, Laravel provides rich features and flexibility to make development easy. SQL Query Logging is the most common way to debug any application. Today, I will explain Log all SQL Queries in your Laravel application.
There are multiple ways to create SQL Query Log
Default Log file
You can log all sql queries in default laravel log file laravel.log which is located at “storage/logs”. To log SQL queries, we need to add the following code snippet in the “AppServiceProvider.php” file in the “boot()” function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | use DB; use Log; ... // Add in boot function DB::listen(function($query) { Log::info( $query->sql, $query->bindings, $query->time ); }); |
Create a custom query log file
If you want to create custom query log file “query.log” under the “storage/logs” directory. Then need to add the following code snippet in the “AppServiceProvider.php” file in the “boot()” function.
1 2 3 4 5 6 7 8 9 10 11 12 | use DB; // Illuminate\Support\Facades\DB; use File; // Illuminate\Support\Facades\File; ... // Add in boot function DB::listen(function($query) { File::append( storage_path('/logs/query.log'), '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $query->sql . ' [' . implode(', ', $query->bindings) . ']' . PHP_EOL . PHP_EOL ); }); |
Read Also: Integrate PayUmoney Payment Gateway
Whenever the model executes then each time query is logged in the “query.log” file. And, log data looks like:
1 2 3 4 5 6 | [2020-01-09 10:24:06] select * from "users" where "id" = ? limit 1 [7] [2020-01-09 10:25:04] select "type" from "in_item" where "code" = ? and "vendor_id" = ? order by "id" desc [400000132365, 1] |
I’m a full-stack developer. My hobby and profession to write blog and programming tips that helps to others. I am a great admirer of PHP, Laravel, Codeigniter, AngularJS, Vue.js, Javascript, JQuery, WordPress, Plugin Development, Theme Development and Bootstrap from the early stage.
Leave a Reply