How to create artisan command in Laravel with arguments support
Laravel
Create your own Command
In Laravel you can write your own customized command. Generally, commands will be stored in app\Console\Commands
.
Generate Command
You can generate a command using the default Laravel artisan command :
php artisan make:command AppointmentReminder
Understanding Command
There is main 2 parts in the console command.
- Signature property
- Handle() method
$signature is the command name where you can specify the command name. if you are giving the name "send:reminder" then you have to fire the full command as follows.
php artisan send:reminder
Defining Arguments
You can define optional and required arguments into curly braces as follow.
protected $signature = 'send:reminder {appointmentID}';
// For the Optional argument you have to define ? in last
'mail:send {appointmentID?}'
Fetching Arguments
After executing the command if the argument is passed you have to fetch it. for that, you can use the default function as follow.
public function handle(): void
{
$appointmentID = $this->argument('appointmeentID');
}
You can use Options in the same manner as we did for the arguments.
Executing Commands from code
Route::post('/send-reminders', function (string $user) {
Artisan::call('send:reminder', [
'appointmentID' => 123
]);
// ...
});