Laravel Artisan is Laravel's built-in command-line interface (CLI) and it's very powerful. Besides the hundreds of built-in commands like php artisan migrate or php artisan make:model, you can also create your own commands. Custom Artisan commands are very useful for automating routine tasks such as cleaning up old data, sending daily reports, or syncing data from an external API.
Creating a New Command
Use Artisan to generate a new command skeleton:
php artisan make:command SendDailyReport
The file is created at app/Console/Commands/SendDailyReport.php. Laravel 11 automatically discovers commands in this folder, so no manual registration is needed.
The Anatomy of a Laravel Command
Open the newly created file and understand its structure:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SendDailyReport extends Command
{
// Signature: the command name and its arguments/options
protected $signature = 'report:daily
{type : Report type (sales/inventory)}
{--email= : Destination email address}
{--dry-run : Run without actually sending the email}';
// Description shown in php artisan list
protected $description = 'Send a daily report to the admin via email';
// Main command logic
public function handle(): int
{
$type = $this->argument('type');
$email = $this->option('email') ?? 'admin@example.com';
$dryRun = $this->option('dry-run');
$this->info("Preparing report of type: {$type}");
if (! in_array($type, ['sales', 'inventory'])) {
$this->error("Invalid report type. Use 'sales' or 'inventory'.");
return Command::FAILURE;
}
// Simulate generating the report
$this->withProgressBar(range(1, 5), function ($step) {
sleep(1); // Simulate a process
});
$this->newLine();
if ($dryRun) {
$this->warn("Dry-run mode: email not sent to {$email}");
} else {
$this->info("The {$type} report was sent successfully to: {$email}");
// Here you would call a Mailable or Notification
}
return Command::SUCCESS;
}
}
This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:
How to Create a Custom Artisan Command in Laravel
More programming tutorials and developer tools are also available at dhiecoderweb.com.
Top comments (0)