8
10

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 TinkerでSQLを確認するには

Last updated at Posted at 2020-07-18

Tinker で実際に SQL を確認したくなったので、少し調べた。
flushQueryLog() が地味に便利かもしれない。

環境

  • Laravel 7.20.0
  • PHP 7.4.7
  • MySQL 5.7.29

前提

Tinker でいろいろ試しながらログを確認したい という場合を想定している。

手順

$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.4.7 — cli) by Justin Hileman
>>> DB::logging();
=> false

>>> DB::enableQueryLog();
=> null

>>> DB::logging();
=> true

>>> App\Memo::find(1);
=> App\Memo {#3940
     id: 1,
     title: "タイトル1",
     body: "本文1",
     is_published: 1,
     created_at: "2020-07-18 13:26:37",
     updated_at: "2020-07-18 13:26:37",
   }

>>> dump(DB::getQueryLog()) && DB::flushQueryLog();
array:1 [
  0 => array:3 [
    "query" => "select * from `memos` where `memos`.`id` = ? limit 1"
    "bindings" => array:1 [
      0 => 1
    ]
    "time" => 103.03
  ]
]
=> false

説明

  • DB::logging()

    • 現在のログ出力設定を確認する
      • true : ログ出力が ON である
      • false : ログ出力が OFF である
  • DB::enableQueryLog()

    • ログ出力を ON にする
    • OFF に戻す場合は DB::disableQueryLog() を使う
  • dump(変数)

  • DB::getQueryLog()

    • ログを取得する
  • DB::flushQueryLog()

    • ログの中身を空っぽにする

蛇足

dd(DB::getQueryLog()) としている記事をよく見かけるけど、 dd() は Tinker を終了させるので、Tinker でいろいろ試したい人にはあんまり向かないように思う。
なので、 dd() のかわりに dump() を使っている。

また、デフォルトでは getQueryLog() をしてもログは消えないけど、連続で確認する場合、一度画面に表示したログは不要だろう。
なので、以下のように、 dump() したら速やかに flushQueryLog() を実行してログを空っぽにしている。

dump(DB::getQueryLog()) && DB::flushQueryLog();
8
10
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
8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?