Skip to content

Instantly share code, notes, and snippets.

@JesseObrien
Last active September 26, 2024 12:40
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;
}
}
@Anatoliy-Petrov
Copy link

Anatoliy-Petrov commented Aug 4, 2020

fullSql

@garygreen Looks like it does not work with '%like%' case, when I use whereRaw('name like %test-name%'), it replaces % with %%

@connor11528
Copy link

laravel-debugbar and/or Telescope will log your queries out too :) This is helpful snippet. Thank you

@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