If you're not using Laravel DebugBar you should really think about it.
Improving the performance of your Laravel app is a lot more than just removing N+1 db problems. DebugBar shows you timings and also model and memory usage.
But if you're not keen, or you can't use DebugBar for some reason (It can be a mission getting it working with API's etc) then a nice solution is to have a little Database Listener which logs all the SQL Queries into your laravel log.
This can also be very useful for debugging problems on staging or live environments as you can turn it on/off easily based on the env/config
How it works:
Add this to your AppServiceProvider's boot method
if (env("SQL_DEBUG_LOG"))
{
DB::listen(function ($query) {
Log::debug("DB: " . $query->sql . "[". implode(",",$query->bindings). "]");
});
}
If you're using it in production I'd also recommend pulling that env into config and using that, as then you can (and should) cache the config
Another issue with it that I've found is if the sql call itself fails, and throws an exception, it's not logged as DB::listen only logs after a successful call and the exception breaks out before it get's back to the listen
If you're having laravel performance issues, another great resource to look at is the eloquent course from Jonathan Reinink
https://eloquent-course.reinink.ca/
Top comments (0)