Laravel 打印请求过程中的所有 SQL

说明

在项目开发中,有时需要打印SQL进行调试,下面介绍打印SQL的方式。

打印单条SQL

DB::enableQueryLog();

DB::getQueryLog();

打印请求过程中的SQL

在AppServiceProvider.php 的 boot 方法加入以下代码即可:

if (config('app.env') === 'local') {
    DB::connection()->enableQueryLog();

    Event::listen(RequestHandled::class, function ($event) {
        if ($event->request->input('sql_debug')) {

            $queries = DB::getQueryLog();

            if (!empty($queries)) {
                foreach ($queries as &$query) {
                    $query['full_query'] = vsprintf(str_replace('?', '%s', $query['query']), $query['bindings']);
                }
            }

            dd($queries);
        }
    });

}

使用

在请求参数中增加 sql_debug ,参数值为 true 时即可打印出请求过程中的所有 SQL 了。

原理

在 kernel.php 的 handle 方法中,处理完成请求后,会 dispatch RequestHandled 事件,所以通过监听这个请求完成的事件就可以了。

下面是 handle 方法:

/**
 * Handle an incoming HTTP request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function handle($request)
{
    try {
        $request->enableHttpMethodParameterOverride();

        $response = $this->sendRequestThroughRouter($request);
    } catch (Exception $e) {
        $this->reportException($e);

        $response = $this->renderException($request, $e);
    } catch (Throwable $e) {
        $this->reportException($e = new FatalThrowableError($e));

        $response = $this->renderException($request, $e);
    }

    $this->app['events']->dispatch(
        new Events\RequestHandled($request, $response)
    );

    return $response;
}

那为什么要在 AppServiceProvider 中配置呢

Application.php 构造函数如下:

/**
 * Create a new Illuminate application instance.
 *
 * @param  string|null  $basePath
 * @return void
 */
public function __construct($basePath = null)
{
    if ($basePath) {
        $this->setBasePath($basePath);
    }

    $this->registerBaseBindings();

    $this->registerBaseServiceProviders();

    $this->registerCoreContainerAliases();
}

注册配置文件中的 服务提供器,代码如下:

/**
 * Register all of the configured providers.
 *
 * @return void
 */
public function registerConfiguredProviders()
{
    (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath()))
                ->load($this->config['app.providers']);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2

直接

\DB::listen(function($query){
dump($query->sql);
});
5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!