DEV Community

Cover image for Laravel 8 Query Log Example
Code And Deploy
Code And Deploy

Posted on

3 2

Laravel 8 Query Log Example

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-8-query-log-example

In this post, I will show you how to implement Laravel 8 Query log. Sometimes need to show the query log and to determine what was the last executed. This is useful when you want to debug the multiple queries in your Laravel application.

In this example I will show you a 3 methods that you can apply in your project.

Example #1

$user = User::select("*")->toSql();
dd($user);
Enter fullscreen mode Exit fullscreen mode

Output:

select * from `users`
Enter fullscreen mode Exit fullscreen mode

Example #2:

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
dd($query);
Enter fullscreen mode Exit fullscreen mode

Output:

array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 30.66
  ]
]
Enter fullscreen mode Exit fullscreen mode

Example #3

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
$query = end($query);
dd($query);
Enter fullscreen mode Exit fullscreen mode

Output:

array:3 [▼
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 22.04
]
Enter fullscreen mode Exit fullscreen mode

Example #4

\DB::enableQueryLog();
$users = \DB::table("users")->get();
$query = \DB::getQueryLog();
dd(end($query));
Enter fullscreen mode Exit fullscreen mode

Output:

array:3 [▼
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 26.94
]
Enter fullscreen mode Exit fullscreen mode

That's it you have now the basic on how to implement Laravel query log.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-query-log-example if you want to download this code.

Happy coding :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series