关于在Laravel4中记录SQL查询,已经有几个问题了,但是我几乎try 了所有的问题,它仍然不能以我想要的方式工作.

Here's my situation

  1. in my php view file, I make AJAX request to the server
  2. 接收AJAX请求并运行原始参数化的Postgres SQL查询(例如.

    DB::select('select * from my_table where id=?', array(1))

如果我使用

Event::listen('illuminate.query', function($sql)
{
  Log::error($sql);
});

I just get "select * from my_table where id=?" as the log message without the ID value actually populated.

如果我使用

$queries = DB::getQueryLog();
$last_query = end($queries);
Log::error(print_r($last_query, true));

I still don't have the final SQL query with the ID populated.

Finally, if I use a logging tool like https://github.com/loic-sharma/profiler - it doesn't display anything since I'm making an AJAX request.

Have I exhausted my options? Is there still another better way?

推荐答案

Here is what I am currently using for logging of sql queries. You should be able to drop this into your main routes file then add 'log' => true into your database config.

if (Config::get('database.log', false))
{           
    Event::listen('illuminate.query', function($query, $bindings, $time, $name)
    {
        $data = compact('bindings', 'time', 'name');

        // Format binding data for sql insertion
        foreach ($bindings as $i => $binding)
        {   
            if ($binding instanceof \DateTime)
            {   
                $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            }
            else if (is_string($binding))
            {   
                $bindings[$i] = "'$binding'";
            }   
        }       

        // Insert bindings into query
        $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
        $query = vsprintf($query, $bindings); 

        Log::info($query, $data);
    });
}

Thanks to Jeemusu answer for the bit about inserting the bindings into the prepared statement.

Laravel相关问答推荐

拉威尔望远镜没有显示请求细节

Livewire 3分页在点击后不更新页面

将 ID 传递给资源控制器进行编辑

模型文件名更改数据库中的表名

在 Laravel 包中的路由上使用显式或隐式模型绑定

前端和管理员分开时未加载laravel 9中间件

Laravel 4:如何将 WHERE 条件应用于 Eloquent 类的所有查询?

Laravel 5.1 - 如何在进度条上设置消息

Laravel transformer vs resource

Laravel 4 定义 RESTful 控制器

使用 vue-router 更改路由时中止所有 Axios 请求

为什么客户凭证应该与 Laravel Passport 中的用户相关联?

在 laravel 6.0 中未定义命令ui

Laravel - 更新时禁用更新时间

Laravel 全部返回 ID 变为 0

扩展模型 == 扩展 Eloquent?

Laravel 验证 pdf mime

如何清理 Laravel Bootstrap 缓存配置文件?

Grammar::parameterize() 必须是数组类型

Laravel 4 控制器模板/Blade - 正确的方法?