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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 2

直接

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

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