Ketika kamu membutuhkan antarmuka command-line (command-line interface / CLI), kamu dapat memanfaatkan fitur Artisan Console. Laravel menyediakan sejumlah perintah Artisan dengan menggunakan memanggil perintah list
php artisan list
Untuk menambahkan perintah Artisan, dapat dibuat dengan perintah make:command. Kita akan membuat sebuah perintah Artisan untuk menampilkan kota seperti pada contoh sebelumnya:
php artisan make:command ViewCities
File perintah Artisan tersebut disimpan di app\Console\ViewCities.php.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ViewCities extends Command
{
protected $signature = 'city:view';
protected $description = 'View cities';
public function __construct()
{
parent::__construct();
}
public function handle()
{
//
}
}
Isikan variabel $signature dengan nama perintah Artisan dan masukkan deskripsinya di variabel $description.
Baris-baris kode yang ada di method handle() akan dieksekusi saat perintah Artisan yang dibuat dijalankan. Berikut contoh kode untuk menampilkan daftar kota:
public function handle()
{
$this->info("Daftar Kota");
$cities = \App\City::all();
foreach ($cities as $city) {
$this->line("- {$city->name}: {$city->map}");
}
}
Agar perintah Artisan dapat digunakan, masukkan class tersebut ke dalam variabel $commands yang ada di file app/Console/Kernel.php
protected $commands = [
...
Commands\ViewCities::class
];
Panggil perintah artisan tersebut dengan perintah:
php artisan city:view

Berikut kode lengkap:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ViewCities extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'city:view';
/**
* The console command description.
*
* @var string
*/
protected $description = 'View cities';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info("Daftar Kota");
$cities = \App\City::all();
foreach ($cities as $city) {
$this->line("- {$city->name}: {$city->map}");
}
}
}
