![見出し画像](https://assets.st-note.com/production/uploads/images/60593189/rectangle_large_type_2_0971832912ffba27f014fa072cd43676.png?width=800)
Laravel8でバッチ処理を作ってみる
Laravel8でバッチを作る必要ができたので、勉強がてらメモ。
コマンドでファイル作成
php artisan make:command exsampleBatch
これで app/Console/Commands以下にexsampleBatch.phpというファイルができると思います。
下記のようなファイルができています。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class exsampleBatch extends Command
{
/**
* The name and signature of the console command.
*
* @var stringC
*/
protected $signature = 'command:name';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
return 0;
}
}
設定
signatureとdescriptionを変更します。
/**
* The name and signature of the console command.
*
* @var stringC
*/
protected $signature = 'command:exsample';
/**
* The console command description.
*
* @var string
*/
protected $description = 'note用のテストバッチです。';
これを設定することで、listコマンド実行するときに一覧に表示されます。
コマンドがわからなくなった場合に、便利なので覚えておきましょう。
php artisan list
~~~~~~~~
command
command:exsample note用のテストバッチです。
※listコマンドを打つとcacheクリアのコマンドもあるので一度見ておくのをオススメします。
処理を書くとこ
最後に処理を書くところはこちらです。
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
return 0;
}
handle内に実行処理を書くことで、バッチ処理完了です。
あとは普通にDB更新処理だったり、メール送信したりといろんなことをやってみましょう。
処理実行
下記コマンドで実行しちゃってください。
php artisan command:exsample
var_dumpなど仕込んで実行されているのを確認してみてください。
以上、バッチの作り方でした!
次回はバッチのタイマーの書き方を書いて行こうかと思います。
この記事が気に入ったらサポートをしてみませんか?