Laravel 實時監聽列印 SQL

994914376發表於2018-03-26

建立監聽器

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);
    }
}

相關文章