laravel打印执行的Sql语句

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

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

有两种方法,

第一种:

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

安装完以后,直接在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)
    {
        $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\ 下看自己的日志吧!

类似这样

[2017-01-02 02:50:09] local.INFO: select count(*) as aggregate from `g9zz_posts`  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_posts` limit 30 offset 0  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_categories` where `g9zz_categories`.`id` in ('1', '6', '5', '3', '4')  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_users` where `g9zz_users`.`id` in ('8', '12', '10', '16', '5')  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_users` where `g9zz_users`.`id` in ('11', '17', '0')  

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


欢迎转载,但请附上原文地址哦,尊重原创,谢谢大家 本文地址: http://www.iphpt.com/detail/75/

当你能力不能满足你的野心的时候,你就该沉下心来学习