laravel打印执行的Sql语句

用laravel,有时候,突然报错,虽然知道是 sql执行的问题,又或者是想知道自己写的语句执行的过程!

这个时候就需要能看到所有语句了…

有两种方法,

第一种:

下载 clockwork 扩展,这个扩展可以在很多框架里调试,比如laravel,lumen,CI等等,很是好用,

GitHub地址:https://github.com/itsgoingd/clockwork

中文地址: http://laravelacademy.org/post/3746.html

安装完以后,直接在firebug里可以看到执行的语句!

第二种:
自己写
执行

php artisan make:listener QueryListener

会生成app/Listeners/QueryListener.php文件

然后把handler修改成下面这样

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function handle(QueryExecuted $event)
    {
        if (getenv('APP_DEBUG')=='true'){
            $sql = str_replace("?", "'%s'", $event->sql);
            $log = vsprintf($sql, $event->bindings);
            \Log::info($log);
        }
    }

}

打开 app/Providers/EventServiceProvider.php ,在 $listen 中添加

protected $listen = [
    'App\Events\SomeEvent' => [
        'App\Listeners\EventListener',
    ],
    'Illuminate\Database\Events\QueryExecuted' => [
        'App\Listeners\QueryListener'
    ]
];

然后在 自己的storage\log\ 下看自己的日志吧!

建议把日志换成daily的,不然日志大小会爆炸的(config/app.php 里的APP_LOG)

HTTPROOT | 自学PHP | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 石头哥 |微信小程序 |木讯 |备案
Copyright © 1998 - 2016 HTTPROOT.COM. All Rights Reserved httproot.com 版权所有