Skip to content

Instantly share code, notes, and snippets.

@JesseObrien
Last active January 31, 2024 06:24
Show Gist options
  • Save JesseObrien/7418983 to your computer and use it in GitHub Desktop.
Save JesseObrien/7418983 to your computer and use it in GitHub Desktop.
Bind parameters into the SQL query for Laravel ORM
<?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;
}
}
@zoispag
Copy link

zoispag commented May 2, 2022

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