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

An overview of every main PHP array function

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to set up an alias to map one directory to another destination

How to Extract Query String (from a URL) Into an Associative Array in PHP

Force trailing slash (redirect if no trailing slash exists) in .htaccess

What is the spaceship operator (<=>) in PHP?

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

What are route patterns in Laravel?

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

How do Invokable Controllers work in Laravel?