Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Created December 22, 2021 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasrulhazim/97451e4445e0b3c403e9bc830d46f84f to your computer and use it in GitHub Desktop.
Save nasrulhazim/97451e4445e0b3c403e9bc830d46f84f to your computer and use it in GitHub Desktop.
A helper to dump sql statement for given query builder in Laravel
​<?php
​use​ ​Illuminate​\​Database​\​Eloquent​\​Builder​;
​if​ (! ​function_exists​(​'dumpSql'​)) {
​    ​function​ ​dumpSql​(​Builder​ ​$​builder​)
​    {
​        ​return​ ​array_reduce​(​$​builder​->​getBindings​(), ​function​ (​$​sql​, ​$​binding​) {
​            ​return​ ​preg_replace​(​'/\?/'​, ​is_numeric​(​$​binding​) ? ​$​binding​ : ​"'"​.​$​binding​.​"'"​, ​$​sql​, ​1​);
​        }, ​$​builder​->​toSql​());
​    }
​}
​if​ (! ​function_exists​(​'logDumpSql'​)) {
​    ​function​ ​logDumpSql​(​Builder​ ​$​query​)
​    {
​        ​logger​()->​debug​(​dumpSql​(​$​query​));
​    }
​}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment