Last active
May 5, 2022 09:55
-
-
Save rseon/51e6bb617de6709ff0d9a308b2ccd1cd to your computer and use it in GitHub Desktop.
Display Laravel queries in PHP files (like the DebugBar but without view)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Display Laravel queries in PHP files (like the DebugBar but without view) | |
*/ | |
/** | |
* 1. Create the helper | |
*/ | |
if (!function_exists('get_db_queries')) { | |
/** | |
* Get queries used in the $callback | |
* | |
* @param \Closure $callback Method calling DB queries | |
* @return Illuminate\Support\Collection ['query binded', 'execution time'] | |
*/ | |
function get_db_queries($callback) | |
{ | |
$queries = collect(); | |
\DB::listen(function ($query) use ($queries) { | |
$queries->push([ | |
'query' => vsprintf(str_replace('?', '%s', $query->sql), collect($query->bindings)->map(function ($binding) { | |
return is_numeric($binding) ? $binding : "'{$binding}'"; | |
})->toArray()), | |
'time' => $query->time | |
]); | |
}); | |
$callback(); | |
return $queries; | |
} | |
} | |
/** | |
* 2. Call it anywhere (like Controller, etc) | |
*/ | |
$queries = get_db_queries(function() use ($MyModel) { | |
$MyModel->methodWithQueryCalls(); | |
}); | |
// Dump it | |
dd($queries); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment