Laravel5. * method for printing the executed SQL statement, laravel5. SQL
This article describes how Laravel5. * prints the executed SQL statement. The details are as follows:
Open app \ Providers \ AppServiceProvider. PHP and add the following content to the boot method:
Earlier than 5.2
// Introduce DB use DB first; // or directly use \ DB: listen (function ($ SQL, $ bindings, $ time) {dump ($ SQL );});
5.2 and later versions
Use DB; // or directly use \ DB: // only one parameter QueryExecuted {#84 rows + SQL: "select * from 'posts' where 'slug' =? Limit 1 "+ bindings: array: 1 [▶] + Time: 0.59 + connection: MySqlConnection {#85▶} + ConnectionName: "mysql"} DB: listen (function ($ SQL) {dump ($ SQL); // echo $ SQL-> SQL; // dump ($ SQL-> bindings) ;}); // if you want to put it in a log file DB: listen (function ($ SQL) {// $ SQL is an object with the properties: // SQL: The query // bindings: the SQL query variables // time: The execution time for the query // connectionName: the name of the connection // To save the executed queries to file: // Process the sq L and the bindings: foreach ($ SQL-> bindings as $ I => $ binding) {if ($ binding instanceof \ DateTime) {$ SQL-> bindings [$ I] = $ binding-> format ('\ 'Y-m-d H: I: s \'');} else {if (is_string ($ binding) {$ SQL-> bindings [$ I] = "'$ binding '";}}} // Insert bindings into query $ query = str_replace (array ('% ','? '), Array (' % ',' % s'), $ SQL-> SQL); $ query = vsprintf ($ query, $ SQL-> bindings ); // Save the query to file $ logFile = fopen (storage_path ('logs '. DIRECTORY_SEPARATOR. date ('Y-m-d '). '_ query. log'), 'a + '); fwrite ($ logFile, date ('Y-m-d H: I: s '). ':'. $ query. PHP_EOL); fclose ($ logFile );});
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.