Skip to content

Instantly share code, notes, and snippets.

@charlesteh
Last active September 4, 2024 05:38
Show Gist options
  • Save charlesteh/3ec129b7f811c03ccd862296aeaae7de to your computer and use it in GitHub Desktop.
Save charlesteh/3ec129b7f811c03ccd862296aeaae7de to your computer and use it in GitHub Desktop.
Get unmasked SQL queries from Eloquent
<?php
if (! function_exists('get_sql_from_eloquent')) {
/**
* A Function to dump SQL query out from an Eloquent object.
*
* @param \Illuminate\Database\Eloquent\Builder $query The Eloquent object.
* @return string The SQL query.
*
* Usage: dd(get_sql_from_eloquent(\App\Models\User::query()));
*
*
*/
function get_sql_from_eloquent(Illuminate\Database\Eloquent\Builder $query): string
{
$sql = $query->toSql();
foreach ($query->getBindings() as $binding) {
$value = is_numeric($binding) ? $binding : "'{$binding}'";
$sql = preg_replace('/\?/', $value, $sql, 1);
}
return $sql;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment