3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelのコンソールで実行されたQueryを出力する方法

Posted at

実際に実行されたQueryが見たい場合、通常のウェブページならdebugbarなりclockworkで簡単に見られますが、artisanコマンドやseederの場合はパッと見る方法が(たぶん)ありません。

こんなのを仕込んでおくと出力されます。

Laravel4.2

Event::listen('illuminate.query', function ($query, $bindings, $time, $name) {
    $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS);
    for ($i = 1; $i < count($backtrace); $i++) {
        $bt = $backtrace[$i];

        if (!isset($bt['file']) || strpos($bt['file'], 'vendor/') !== false) {
            continue;
        }
        if (isset($bt['file'])) {
            echo $bt['file'], ': ';
        }
        if (isset($bt['line'])) {
            echo $bt['line'], ': ';
        }
        echo "\n";
        break;
    }

    foreach ($bindings as $binding) {
        if (is_null($binding)) {
            $binding = 'NULL';
        } elseif (is_string($binding)) {
            $binding = "'" . $binding . "'";
        }
        $query = preg_replace('/\?/', $binding, $query, 1);
    }

    echo $query, ";\n";
    echo '----------------------------------------------------------------------', "\n";
});

Laravel5.2

// ...
$app = app();
$dispatcher = $app['events'];

$dispatcher->listen('Illuminate\Database\Events\QueryExecuted', array($this, 'logQuery'));
// ...
public function logQuery($event)
{
    $query = $event->sql;
    $bindings = $event->bindings;

    $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS);
    for ($i = 1; $i < count($backtrace); $i++) {
        $bt = $backtrace[$i];

        if (!isset($bt['file']) || strpos($bt['file'], 'vendor/') !== false) {
            continue;
        }
        if (isset($bt['file'])) {
            echo $bt['file'], ': ';
        }
        if (isset($bt['line'])) {
            echo $bt['line'], ': ';
        }
        echo "\n";
        break;
    }

    foreach ($bindings as $binding) {
        if (is_null($binding)) {
            $binding = 'NULL';
        } elseif (is_string($binding)) {
            $binding = "'" . $binding . "'";
        }
        $query = preg_replace('/\?/', $binding, $query, 1);
    }

    echo $query, ";\n";
    echo '----------------------------------------------------------------------', "\n";
}
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?