Laravel Count Number of Queries to the Database

If you want to know how many times your Laravel query is hitting the database you can use this snippet by @Tarasovych from StackOverflow.

$counter = 0;
\DB::listen(function($sql) {
    $counter++; //increment for each query was run
});
// Execute your query here
echo $counter;

Pretty handy!

2 thoughts on “Laravel Count Number of Queries to the Database”

    • You should pass it by reference, otherwise value is not written to the variable outside function:
      Final code is:

      $counter = 0;

      \DB::listen(function() use (&$counter) {
      $counter++; //increment for each query was run
      });

      echo $counter;

      Reply

Leave a Comment