Last active
September 30, 2016 12:19
-
-
Save IonutBajescu/e7e1ff4dcd7c0fd39bf8d534f0e8c126 to your computer and use it in GitHub Desktop.
Dump the laravel query builder as valid SQL
This file contains 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 | |
if (!function_exists('dump_builder')) { | |
/** | |
* @param Builder $builder | |
*/ | |
function dump_builder($builder, array $outputAlso = []) | |
{ | |
$sql_string = $builder->toSql(); | |
$params = $builder->getBindings(); | |
if (!empty($params)) { | |
$indexed = $params == array_values($params); | |
foreach ($params as $k => $v) { | |
if (is_object($v)) { | |
if ($v instanceof \DateTime) { | |
$v = "'". $v->format('Y-m-d H:i:s') . "'"; | |
} else { | |
continue; | |
} | |
} elseif (is_string($v)) { | |
$v = "'$v'"; | |
} elseif ($v === null) { | |
$v = 'NULL'; | |
} elseif (is_array($v)) { | |
$v = implode(',', $v); | |
} | |
if ($indexed) { | |
$sql_string = preg_replace('/\?/', $v, $sql_string, 1); | |
} else { | |
if ($k[0] != ':') { | |
$k = ':'.$k; | |
} //add leading colon if it was left out | |
$sql_string = str_replace($k, $v, $sql_string); | |
} | |
} | |
} | |
array_unshift($outputAlso, 'SQL: '.$sql_string); | |
call_user_func_array('dd', $outputAlso); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment