Last active
September 4, 2024 05:38
-
-
Save charlesteh/3ec129b7f811c03ccd862296aeaae7de to your computer and use it in GitHub Desktop.
Get unmasked SQL queries from Eloquent
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 | |
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