Last active
September 26, 2024 12:40
-
-
Save JesseObrien/7418983 to your computer and use it in GitHub Desktop.
Bind parameters into the SQL query for Laravel ORM
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 | |
class MyModel extends Eloquent { | |
public function getSql() | |
{ | |
$builder = $this->getBuilder(); | |
$sql = $builder->toSql(); | |
foreach($builder->getBindings() as $binding) | |
{ | |
$value = is_numeric($binding) ? $binding : "'".$binding."'"; | |
$sql = preg_replace('/\?/', $value, $sql, 1); | |
} | |
return $sql; | |
} | |
} | |
@garygreen awesome. Thanks man!
@JesseObrien thank you!!.
fullSql
@garygreen Looks like it does not work with '%like%' case, when I use whereRaw('name like %test-name%'), it replaces % with %%
laravel-debugbar and/or Telescope will log your queries out too :) This is helpful snippet. Thank you
Slight variation for Laravel 9:
\Illuminate\Database\Query\Builder::macro('toRawSql', fn (): string => str($this->toSql())
->replaceArray('?', collect($this->getConnection()->prepareBindings($this->getBindings()))
->map(fn ($binding) => is_numeric($binding) ? $binding : str($binding)->replace(['\\', "'"], ['\\\\', "\'"])->prepend("'")->append("'")->__toString())
->toArray()
)
);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's updated version which fixes quite a few binding value bugs and also aligns more closely with how Laravel serializes
true
/false
values into1
/0
Examples:
Output: