この記事で解決できる悩み

こんな悩みを解決できる記事を書きました!
僕は現役フリーランスエンジニア(歴9年)で、資格は13個保有しています。
「LaravelでSQLのクエリログを出力する方法を知りたい」とお考えではありませんか?
結論からお伝えすると、LaravelでSQLのクエリログを出力するのは超簡単です。



ミドルウェアを作成すればいい感じに共通化できます♪
ということで、本記事ではLaravelでSQLのクエリログを出力する方法を解説します。





すぐ読み終わるので、ぜひ最後まで読んでくださいませ。
目次
【Laravel】SQLのクエリログを出力する方法
早速ですが、LaravelでSQLのクエリログを出力する方法を解説します。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class QueryLogger
{
public function handle($request, Closure $next)
{
// クエリログを有効化する
DB::enableQueryLog();
$response = $next($request);
// クエリログを取得する
$queries = DB::getQueryLog();
Log::info($queries);
return $response;
}
}
「enableQueryLog」と「getQueryLog」を使えば、ログファイルにクエリログを出力できます。



超簡単…
まとめ
今回は、LaravelでSQLのクエリログを出力する方法について解説しました。
以下が本記事のまとめになります。
- おすすめ本
Laravelの勉強なら「PHPフレームワーク Laravel入門 第2版



最後までお読みいただき、ありがとうございました!
- クソおすすめ本



海外のエンジニアがどういった思考で働いているかが理解できます。
海外に行く気はないけど海外エンジニアの動向が気になる雑魚エンジニアにおすすめです(本当におすすめな本しか紹介しないのでご安心を)。