11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

laravelで実際に発行されたSQLと処理時間を確認する

Last updated at Posted at 2022-11-13

はじめに

いつも忘れるので備忘録として残しておく

コード

DB::enableQueryLog();
$time_start = microtime(true);

//計測したい処理やSQL(複数発行されれば複数dumpされる)
$user = User::where('id', 10000)->get();

$time = microtime(true) - $time_start;
dump($time);
dd(DB::getQueryLog());

発行されるSQLを確認したい時

$user = User::where('id', 10000)->toSql();
dd($user);

おまけ

取得したコレクションを配列にしてログに吐く

$user = User::where('id', 10000)->get();
LOG::info(print_r($user->toArray(), true));

おまけその2

LaravelのAppServiceProvider.phpに下記追加することでstorage/logs/laravel.logに出力される

public function boot()
    {
        \Illuminate\Support\Facades\DB::listen(function ($query) {
            \Illuminate\Support\Facades\Log::info('SQL Query: ' . $query->sql);
            \Illuminate\Support\Facades\Log::info('Bindings: ' . json_encode($query->bindings));
            \Illuminate\Support\Facades\Log::info('Time: ' . $query->time . 'ms');
        });
    }
11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?