Problem: You have repetitive tasks like data cleanup, report generation, or batch processing that you want to automate through the command line.
Solution:
// Generate command skeleton
php artisan make:command SendNewsletterCommand
// In app/Console/Commands/SendNewsletterCommand.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use App\Mail\NewsletterMail;
use Illuminate\Support\Facades\Mail;
class SendNewsletterCommand extends Command
{
// Command signature - how you call it
protected $signature = 'newsletter:send
{type : The type of newsletter to send}
{--test : Send only to test users}
{--limit=100 : Number of users to process}';
// Command description shown in artisan list
protected $description = 'Send newsletter to subscribed users';
public function handle()
{
$type = $this->argument('type');
$isTest = $this->option('test');
$limit = $this->option('limit');
$this->info("Sending {$type} newsletter...");
$query = User::where('subscribed', true);
if ($isTest) {
$query->where('is_test', true);
}
$users = $query->limit($limit)->get();
$bar = $this->output->createProgressBar($users->count());
foreach ($users as $user) {
Mail::to($user)->queue(new NewsletterMail($type));
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info('Newsletter sent successfully!');
return Command::SUCCESS;
}
}
// Usage
php artisan newsletter:send weekly
php artisan newsletter:send daily --test --limit=10
// Schedule in app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('newsletter:send daily')->dailyAt('09:00');
}
Why it works: Artisan commands have access to your entire Laravel application. The signature
property defines arguments and options using a simple syntax. The handle()
method contains your command logic with access to helpful console methods.
Pro tips: Use Command::SUCCESS
(0) or Command::FAILURE
(1) as return values. Add --no-interaction
flag support for automated environments.
Table Of Contents
Related Topics
- How to Run a Scheduled Task on a Single Server - Schedule your custom commands
- How to Prioritize Jobs on a Queue - Queue tasks from commands
Share this article
Add Comment
No comments yet. Be the first to comment!