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 Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay