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 an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

What is the difference between integration and unit tests?

How to provide a default model object for relationships?

How to find the 2nd most common item in an array?

How to block an IP address in .htaccess

What is YAGNI?

How to find the index of a value in an array in JS?

How to add and remove items to an array in JS?

What is an example of an object literal?