How to show (or log) all SQL queries executed by Laravel

Laravel: How to show (or log) all SQL queries executed by Laravel

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

  1. $posts = Posts::where("type",$type)->get();
  2. // or as SQL statement
  3. $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:

  1. // put this somewhere...
  2. DB::connection()->enableQueryLog();
  3. // run some queries
  4. Posts::where("title","test")->get();
  5. User::find(1);
  6.  
  7. // then loop through this:
  8. $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)

  1. Event::listen('illuminate.query', function($query)
  2. {
  3.     dump($query);
  4. });

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

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to show (or log) all SQL queries executed by Laravel

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to find the average value of items in a Laravel Collection?

How to find out which php.ini file PHP is using?

How to check if a user is logged in, inside a blade file?

When is __destruct called in PHP?

How to query mysql using PDO in PHP?

How to manually write your own pagination in PHP

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to add the CSRF (Cross-site request forgery) token in Laravel?

How to select all rows for a certain month (or day, year or time), using Eloquent