DEV Community

benittobeny34
benittobeny34

Posted on

3 1

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!!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more