Description
Laravel has a very flexible database operation scheme, this article introduces a simple method to get all the SQL statements.
1. Turn on QueryLog
We need to call the following methods to tell the framework to start logging SQL requests:
Db::enablequerylog ();
We can consider placing this code in the Beforemiddleware middleware (see here) and using the following command to generate the Beforemiddleware:
PHP Artisan Make:middleware Beforemiddleware
The above command generates a app/http/middleware/beforemiddleware.php file, within the handle method of this file:
Public function handle ($request, Closure $next) { db::enablequerylog (); Return $next ($request);}
2. Get QueryLog
After QueryLog is turned on, we can use the following methods to get to the executed SQL:
$queries = Db::getquerylog ();
If you want to get all the QueryLog, you can put the code in Aftermiddleware.
Use the following command to create the Aftermiddleware (document see here):
PHP Artisan Make:middleware Aftermiddleware
A app/http/middleware/aftermiddleware.php file is generated, within the handle method of this file:
Public function handle ($request, Closure $next) { $response = $next ($request); Retrieve all executed queries $queries = Db::getquerylog (); Code to save query logs in a file //return response return $response; }