Last active
November 11, 2017 09:55
-
-
Save Vasiliy-Bondarenko/c5132f1680308e269cedddc467dd9bf8 to your computer and use it in GitHub Desktop.
Eloquent query builder macros (for article: https://medium.com/@vasiliybondarenko/debugging-eloquent-queries-in-laravel-2464684d29bf)
This file contains hidden or 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\ServiceProvider; | |
use Log; | |
use Route; | |
class AppServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
$this->macros(); | |
} | |
/** | |
* Register any application services. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
} | |
protected function macros() | |
{ | |
Builder::macro("toSqlWithBindings", function(){ | |
$sql = $this->toSql(); | |
foreach($this->getBindings() as $binding) | |
{ | |
$value = is_numeric($binding) ? $binding : "'$binding'"; | |
$sql = preg_replace('/\?/', $value, $sql, 1); | |
} | |
return $sql; | |
}); | |
Builder::macro("dd", function(){ | |
if (func_num_args() === 1) { | |
$message = func_get_arg(0); | |
} | |
var_dump((empty($message) ? "" : $message . ": ") . $this->toSqlWithBindings()); | |
dd($this->get()); | |
}); | |
Builder::macro("dump", function(){ | |
if (func_num_args() === 1) { | |
$message = func_get_arg(0); | |
} | |
var_dump((empty($message) ? "" : $message . ": ") . $this->toSqlWithBindings()); | |
return $this; | |
}); | |
Builder::macro("log", function(){ | |
if (func_num_args() === 1) { | |
$message = func_get_arg(0); | |
} | |
Log::debug((empty($message) ? "" : $message . ": ") . $this->toSqlWithBindings()); | |
return $this; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment