debugbarを使うとコントローラでのDB処理に使用されるSQL文をブラウザ画面でデバッグ文をわざわざ挿入することなしに見ることができます。しかし、php artisanのコマンドラインの実行では同様なことできません。さて、どうしたらよいでしょうか?
まず、テストコマンドの作成から、
$ php artisan make:command TestCommand
この実行で、TestCommand.php が作成されます。
これを以下のように編集します。
namespace App\Console\Commands;
use App\User;
use Illuminate\Console\Command;
class TestCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'テストコマンド';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$count = User::count();
echo "会員の数:$count\n";
return 0;
}
}
まず、通常のコマンドラインからの実行で動作確認です。
$ php artisan command:test 会員の数:1
大丈夫ですね。
さて、その実行でどのようなSQL文が実行されているかをチェックするには、そう、tinkerの登場です。
以下はtinkerの1セッションですが、説明のために分割されているので注意を。
$ php artisan tinker Psy Shell v0.10.4 (PHP 7.3.14 — cli) by Justin Hileman
まず、DBクエリのログ機能をオンにします。
>>> DB::enableQueryLog(); => null
次に、コマンドの実行です。そうです、Artisan::call()の関数の引数にコマンド名を指定するだけなのです。
>>> Artisan::call('command:test');
会員の数:1
=> 0
次に、貯めたログを出力します。
>>> DB::getQueryLog();
=> [
[
"query" => "select count(*) as aggregate from `users`",
"bindings" => [],
"time" => 14.32,
],
]
>>>
SQL文が見れましたね。
DB::enableQueryLog()などを毎回毎回tinkerのセッションでタイプするのが面倒なら、以前のこの記事のようにブートストラップのファイルを作成しておくと、
$ php artisan tinker ~/tinker.php
>>> Artisan::call('command:test');
会員の数:1
=> 0
>>> sql()
=> [
[
"query" => "select count(*) as aggregate from `users`",
"bindings" => [],
"time" => 14.29,
],
]
>>>
と簡単になります。
私は、シェルのエイリアスとして、.zshrcファイルに入れています。
... alias tinker='php artisan tinker ~/tinker.php' ...メルマガ購読の申し込みはこちらから。
