Skip to content

Console command

Names: use kebab-case

The names given to artisan commands SHOULD all be kebab-cased.

diff
-php artisan deleteOldRecords
-php artisan delete_old_records
+php artisan delete-old-records

Use handle() method dependency injection

Inject any dependencies in the handle() method instead of in the constructor. Laravel initiates ALL console commands on every artisan call, for this reason console command class constructors should be fast and not contain any heavy logic (incl. DI).

Output: use verbosity levels

Use different verbosity levels.

php
$this->info('Updating Articles...', 'v');
// ...
foreach($articles as $article) {
    // ...
    $this->info("\t Article #{$article->id} has been updated", 'vvv');
}

$this->info("{$articles->count()} Articles has been updated");
  1. quiet mode: only errors and important warnings.
  2. normal mode: errors, all warnings and general feedback like All OK, processed XX records!.
  3. v, vv, vvv modes: errors, warnings and any additional info.

The idea behind it is to send email with console command outputs only when output is present (not empty).

Exit with proper code

Use non-zero exit codes if a command execution failed (alternatively, throw an exception — the script will also exit with code 1). This allows using global on-error handlers, e.g. for automated reporting about failed console commands, please see \Illuminate\Console\Scheduling\Event::emailOutputOnFailure as an example.