Skip to content

Instantly share code, notes, and snippets.

@IonutBajescu
Last active September 30, 2016 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IonutBajescu/e7e1ff4dcd7c0fd39bf8d534f0e8c126 to your computer and use it in GitHub Desktop.
Save IonutBajescu/e7e1ff4dcd7c0fd39bf8d534f0e8c126 to your computer and use it in GitHub Desktop.
Dump the laravel query builder as valid SQL
<?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