Cara Membuat Custom Artisan Command di Laravel 12
Artisan bawaan Laravel sudah mencakup banyak kebutuhan. Tapi kadang Anda butuh command yang spesifik untuk proyek Anda, misalnya generate laporan harian, kirim email batch, atau sync data dari API eksternal.
Di sinilah custom Artisan command berguna. Artikel ini menunjukkan cara membuat, mengatur parameter, dan menjalankan scheduled command di Laravel 12.
Membuat Custom Command
Gunakan Artisan untuk generate skeleton command:
php artisan make:command SendDailyReport
File dibuat di app/Console/Commands/SendDailyReport.php:
<?php
namespace AppConsoleCommands;
use IlluminateConsoleCommand;
class SendDailyReport extends Command
{
protected $signature = 'report:daily';
protected $description = 'Send daily sales report to managers';
public function handle(): int
{
// logika command di sini
return Command::SUCCESS;
}
}
Jalankan:
php artisan report:daily
Menambahkan Argumen dan Opsi
Command yang berguna biasanya butuh input. Ada dua jenis: argumen (wajib) dan opsi (opsional dengan --).
protected $signature = 'report:send
{type : Tipe laporan: sales atau inventory}
{--date= : Tanggal laporan (default: hari ini)}
{--dry-run : Simulasi tanpa kirim email}';
Cara mengakses di dalam handle():
public function handle(): int
{
$type = $this->argument('type');
$date = $this->option('date') ?? now()->toDateString();
$dryRun = $this->option('dry-run');
$this->info("Membuat laporan {$type} untuk tanggal {$date}...");
if ($dryRun) {
$this->warn('Mode dry-run: email tidak akan dikirim.');
}
// proses laporan...
$this->info('Selesai.');
return Command::SUCCESS;
}
Contoh penggunaan:
php artisan report:send sales
php artisan report:send sales --date=2025-04-01
php artisan report:send inventory --dry-run
Output yang Informatif
Artisan menyediakan beberapa helper untuk output yang bersih:
$this->info('Pesan biasa'); // hijau
$this->error('Ada error!'); // merah
$this->warn('Perhatian'); // kuning
$this->line('Teks biasa'); // putih
$this->comment('// komentar'); // abu-abu
// Progress bar untuk proses batch
$users = User::all();
$bar = $this->output->createProgressBar(count($users));
$bar->start();
foreach ($users as $user) {
// proses
$bar->advance();
}
$bar->finish();
Dependency Injection di Custom Command
Inject service lewat constructor, sama seperti controller:
<?php
namespace AppConsoleCommands;
use AppServicesReportService;
use AppServicesMailService;
use IlluminateConsoleCommand;
class SendDailyReport extends Command
{
protected $signature = 'report:daily {--date=}';
protected $description = 'Send daily report via email';
public function __construct(
private ReportService $reportService,
private MailService $mailService,
) {
parent::__construct();
}
public function handle(): int
{
$date = $this->option('date') ?? now()->toDateString();
$report = $this->reportService->generate($date);
if ($report->isEmpty()) {
$this->warn("Tidak ada data untuk tanggal {$date}.");
return Command::SUCCESS;
}
$this->mailService->sendReport($report);
$this->info("Laporan {$date} berhasil dikirim ke " . $report->recipientCount() . " penerima.");
return Command::SUCCESS;
}
}
Menjadwalkan Command Otomatis
Di Laravel 12, jadwal command diatur di routes/console.php — bukan lagi di app/Console/Kernel.php:
<?php
use IlluminateSupportFacadesSchedule;
// Kirim laporan setiap hari jam 7 pagi
Schedule::command('report:daily')->dailyAt('07:00');
// Bersihkan log setiap minggu
Schedule::command('log:cleanup')->weekly();
// Sync produk setiap 30 menit
Schedule::command('products:sync')->everyThirtyMinutes();
// Jalankan khusus hari kerja
Schedule::command('report:daily')->weekdays()->at('08:00');
Tambahkan satu baris ke crontab server untuk menjalankan scheduler setiap menit:
* * * * * cd /var/www/html && php artisan schedule:run >> /dev/null 2>&1
Testing Custom Command
Laravel menyediakan helper untuk test command tanpa harus jalankan manual:
public function test_report_command_runs_successfully(): void
{
$this->artisan('report:daily')
->expectsOutput('Laporan berhasil dikirim')
->assertExitCode(0);
}
// Test dengan argumen
public function test_report_with_date(): void
{
$this->artisan('report:send', [
'type' => 'sales',
'--date' => '2025-04-01',
])->assertExitCode(0);
}
Baca Juga
- Command Artisan yang Paling Sering Dipakai di Laravel
- Tutorial Laravel 12 Job Batching untuk Proses Background
Kalau Anda butuh tim untuk membangun dan maintain aplikasi Laravel Anda, lihat layanan pengembangan aplikasi kami.
Ingin Membaca Artikel Lainnya?
Temukan lebih banyak insight dan tips tentang teknologi dan bisnis digital.
Lihat Semua Artikel