DEV Community

benittobeny34
benittobeny34

Posted on

Laravel: Log Sql Query With It's Bindings

Most often laravel dev prefer to log the sql query by using below snippet.

DB::listen(function ($query) {
    info('Query', [
    "Query" => $query->sql,
    "Bindings" => $query->bindings,
    "Time" => $query->time,
  ]);
});
Enter fullscreen mode Exit fullscreen mode

But the drawback of this is it split out the query, sql bindings and it's time.

we can do it in a better way to combine the query and it's bindings by using laravel Macroable Trait.

Add the Below snippet in AppServiceProvider and you are good to go.

Builder::macro('toSqlWithBindings', function () {
  $bindings = array_map(fn($value) => 
                is_numeric($value) ? $value : "'{$value}'",
                $this->getBindings()
            );
            return Str::replaceArray(
             '?', $bindings, $this->toSql()
           );
        });
Enter fullscreen mode Exit fullscreen mode

Most of the laravel illuminate classes are by default uses Macroable Trait. By Using that we can add our custom function to that illuminate classes. These functions are available as class function. so we can here chain the custom function to query builder.

$query = User::where('name', 'like' , '%admin%');

$query->toSqlWithBindings();
Enter fullscreen mode Exit fullscreen mode

Output

select * from `users` where `name` like '%admin%' and `users`.`deleted_at` is null`
Enter fullscreen mode Exit fullscreen mode

Keep Learning!!

Top comments (0)