Debug Database Query in Laravel

Submitted by Mahmoud_Zalt - 8 years ago

Don't forget to add the `DATABASE_QUERIES_DEBUG` in the .env file. Call this function `$this->debugDatabaseQueries()` from any service provider `register` function:

public function debugDatabaseQueries($terminal = true)
{
    if (env('DATABASE_QUERIES_DEBUG', true)) {
        \DB::listen(function ($query, $bindings, $time, $connection) use($terminal) {
            $fullQuery = vsprintf(str_replace(array('%', '?'), array('%%', '%s'), $query), $bindings);

            $text = $connection . ' (' . $time . '): ' . $fullQuery;

            if($terminal) dump($text);

            \Log::info($text);
        });
    }
}