Home > PHP Framework > Laravel > body text

SQL Debug Tips in Laravel

Guanhui
Release: 2020-06-12 17:56:19
forward
3136 people have browsed it

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). "]");
        });
    }
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template