How to show (or log) all SQL queries executed by Laravel
October 26, 2018
There are a few ways to show the SQL queries that are generated and executed by Laravel
toSql()
- You can replace ->get()
(or ->paginate()
) with ->toSql()
to return a string of the SQL query that was generated
<?php
$posts = Posts::where("type",$type)->get();
// or as SQL statement
$postsSql = Posts::where("type",$type)->toSql();
But maybe you want to see all of the queries that Laravel executes for each request?
Query Logging - you can enable the query log, then somewhere else loop through each logged query:
<?php
// put this somewhere...
DB::connection()->enableQueryLog();
// run some queries
Posts::where("title","test")->get();
User::find(1);
// then loop through this:
$queries = DB::getQueryLog();
Or add a event listener for each query - Put this in your AppServiceProvider (or another file, such as your routes file or even in a controller)
<?php
Event::listen('illuminate.query', function($query)
{
dump($query);
});
Just remember to take these bits of code out before pushing the changes to production!