==== # Creating a Custom Laravel Artisan Command ## Overview Laravel Artisan commands allow you to create custom CLI commands to automate repetitive tasks in your application. Here's a comprehensive guide on how to create one. ## Step 1: Generate the Command Use the Artisan make command to generate a new command class: ```bash php artisan make:command SendEmailReport ``` This creates a new file at `app/Console/Commands/SendEmailReport.php` ## Step 2: Configure the Command Open the generated file and configure the command properties: ```php argument('user'); $queue = $this->option('queue'); // Display output $this->info('Sending email report...'); // Your business logic here // Example: Send email, process data, etc. // Progress bar example $users = User::all(); $bar = $this->output->createProgressBar(count($users)); foreach ($users as $user) { // Process user $bar->advance(); } $bar->finish(); // Success message $this->info("\nEmail report sent successfully!"); return Command::SUCCESS; } ``` ## Step 5: Use Input/Output Methods Laravel provides helpful methods for interacting with the user: ```php public function handle() { // Ask for input $name = $this->ask('What is your name?'); // Secret input (password) $password = $this->secret('Enter password'); // Confirmation if ($this->confirm('Do you want to continue?')) { // Continue } // Choice selection $role = $this->choice('Select role', ['admin', 'user', 'guest']); // Display messages $this->info('Information message'); $this->error('Error message'); $this->warn('Warning message'); $this->line('Regular message'); // Table output $this->table( ['Name', 'Email'], [ ['John', 'john@example.com'], ['Jane', 'jane@example.com'] ] ); } ``` ## Step 6: Run the Command Execute your custom command: ```bash # Basic execution php artisan email:send-report # With arguments php artisan email:send-report john@example.com # With options php artisan email:send-report --queue # With both php artisan email:send-report john@example.com --queue ``` ## Step 7: Schedule the Command (Optional) To run the command automatically, add it to `app/Console/Kernel.php`: ```php protected function schedule(Schedule $schedule) { $schedule->command('email:send-report') ->daily() ->at('09:00'); } ``` ## Complete Example ```php argument('user_id'); $type = $this->option('type'); $user = User::find($userId); if (!$user) { $this->error('User not found!'); return Command::FAILURE; } $this->info("Sending {$type} report to {$user->email}..."); Mail::to($user->email)->send(new DailyReport($user)); $this->info('Report sent successfully!'); return Command::SUCCESS; } } ``` This creates a fully functional custom Artisan command that you can use and modify for your specific needs!