Home  >  Article  >  PHP Framework  >  SQL Debug Tips in Laravel

SQL Debug Tips in Laravel

Guanhui
Guanhuiforward
2020-06-12 17:56:193135browse

SQL Debug Tips in Laravel

For some reasons, you cannot use Laravel DebugBar, this article may help you.

Optimizing Laravel applications goes far beyond eliminating the N 1 problem. Proper use of Laravel DebugBar can provide reasonable solutions to problems such as model memory usage and SQL query timeliness.

Maybe you don’t like to use Laravel DebugBar, or you can’t use it for some reasons (such as the development of interface-based applications), then Database Listener will be a good method, it will record your SQL query to log.

This applies equally to production environments and test environments. You can easily control whether it is enabled through env or config.

How to use:

Add this to the startup method of your AppServiceProvider

 if (env("SQL_DEBUG_LOG"))
    {
        DB::listen(function ($query) {
            Log::debug("DB: " . $query->sql . "[".  implode(",",$query->bindings). "]");
        });
    }

If you use it in a production environment, I suggest you put it in config Put the configuration information into env, and then you can (and should) cache this config information

I found another problem is that if the sql call itself fails, an exception will be thrown, and it will listen before the successful call. DB::listen does not log, and the exception occurs before returning to the listener.

Recommended tutorials: "PHP Tutorial" "Laravel Tutorial"

The above is the detailed content of SQL Debug Tips in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete