Last active
April 9, 2021 08:53
-
-
Save loburets/ced834cf853d5ce21e5e4e0cb66dd309 to your computer and use it in GitHub Desktop.
To get mysql query from laravel with embed parameters of the binding
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 | |
// Use your query before you make get(), first() etc | |
$query = \Model::where()->join()->etc(); | |
$sql = $query->toSql(); | |
$sql = str_replace('"', '`', $sql); | |
// just for the raw queries too look normal in the console: | |
$sql = str_replace("\n", ' ', $sql); | |
$sql = str_replace("\t", ' ', $sql); | |
foreach ($query->getBindings() as $binding) { | |
if (!is_numeric($binding)) { | |
$binding = '"' . $binding . '"'; | |
} | |
$sql = preg_replace('/' . preg_quote('?') . '/', $binding, $sql, 1); | |
} | |
dump($sql); | |
// or for query logs: | |
$logs = \DB::getQueryLog(); | |
foreach ($logs as $log) { | |
$log['query'] = str_replace('"', '`', $log['query']); | |
// just for the raw queries too look normal in the console: | |
$log['query'] = str_replace("\n", ' ', $log['query']); | |
$log['query'] = str_replace("\t", ' ', $log['query']); | |
foreach ($log['bindings'] as $binding) { | |
if (!is_numeric($binding)) { | |
$binding = '"' . $binding . '"'; | |
} | |
$log['query'] = preg_replace('/' . preg_quote('?') . '/', $binding, $log['query'], 1); | |
} | |
dump($log['time'] . 'ms: ' . $log['query']); | |
} |
Author
loburets
commented
Apr 6, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment