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

栏目: PHP · 数据库 · 发布时间: 7年前

内容简介: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']);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

互联网爆破术:快速掌握互联网运营全链条实战技巧

互联网爆破术:快速掌握互联网运营全链条实战技巧

茶文 / 电子工业出版社 / 2018-7 / 49.00元

《互联网爆破术:快速掌握互联网运营全链条实战技巧》是一本实用的互联网运营书籍,可以让读者快速掌握运营全链条的干货技巧和相关模型,涵盖如何有效寻找市场的需求爆破点,通过测试一步步放大并引爆,直至赢利。《互联网爆破术:快速掌握互联网运营全链条实战技巧》非常适合互联网运营人员及互联网创业者阅读,它可以帮读者快速了解互联网运营的核心技巧,并用最低的成本取得成功。本书5大特色:快速入门、实战干货、低成本、系......一起来看看 《互联网爆破术:快速掌握互联网运营全链条实战技巧》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具