Laravel 实时监听打印 SQL

创建监听器

php artisan make:listener QueryListener --event=Illuminate\\Database\\Events\\QueryExecuted

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

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

打开QueryListener文件

use \Log;
public function handle (QueryExecuted $event)
{
    if (env('APP_ENV', 'production') == 'local') {
        $sql = str_replace("?", "'%s'", $event->sql);
        $log = vsprintf($sql, $event->bindings);
        Log::info($log);
    }
}

本文章首发在 Laravel China 社区