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

What are the predefined variables in PHP?

How to add the default charset to UTF-8 in .htaccess

What are generators in PHP, and how do they compare to arrays?

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

How to find the intersection (same values) from two arrays?

How to force gzip compression in Apache with .htaccess

What kind of database field type should you (normally) use for foreign keys?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

What is the loop variable in a @foreach loop in Blade?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess