Created
August 13, 2021 20:02
-
-
Save shawnlindstrom/6ec62fb0fa6f6861de9a7a899c5d2065 to your computer and use it in GitHub Desktop.
Laravel to SQL with Bindings Macro
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 | |
namespace App\Providers; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Support\ServiceProvider; | |
class MacroServiceProvider extends ServiceProvider | |
{ | |
public function register() | |
{ | |
/** | |
* Borrowed from Telescop | |
* @see https://github.com/laravel/telescope/blob/4.x/src/Watchers/QueryWatcher.php#L85 | |
**/ | |
Builder::macro('toRawSql', function() { | |
$sql = $this->toSql(); | |
foreach ($this->getBindings() as $key => $binding) { | |
$regex = is_numeric($key) | |
? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/" | |
: "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"; | |
if ($binding === null) { | |
$binding = 'null'; | |
} elseif (! is_int($binding) && ! is_float($binding)) { | |
$binding = DB::connection()->getPdo()->quote($binding); | |
} | |
$sql = preg_replace($regex, $binding, $sql, 1); | |
} | |
return $sql; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment