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

$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:

// put this somewhere...
// run some queries
// 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)

Event::listen('illuminate.query', function($query)

Just remember to take these bits of code out before pushing the changes to production!