Skip to content

Instantly share code, notes, and snippets.

@therobfonz
Created July 15, 2021 19:18
Show Gist options
  • Save therobfonz/ca71939c3b76fb24e125f1d80e48380a to your computer and use it in GitHub Desktop.
Save therobfonz/ca71939c3b76fb24e125f1d80e48380a to your computer and use it in GitHub Desktop.
Eloquent Query Builder Macro to output raw sql
use Illuminate\Database\Eloquent\Builder;
Builder::macro('toRawSql', function(){
return array_reduce($this->getBindings(), function($sql, $binding){
return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
}, $this->toSql());
});
// use
Model::where('field', 'value)->toRawSql();
// output
select * from model where field = 'value';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment