Artisan Console
Introduction
Artisan is the command line interface included with Laravel. Artisan exists at the root of your application as the artisan script and provides a number of helpful commands that can assist you while you build your application. To view a list of all available Artisan commands, you may use the list command:
php artisan list
Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, precede the name of the command with help:
php artisan help migrate
Laravel Sail
If you are using Laravel Sail as your local development environment, remember to use the sail command line to invoke Artisan commands. Sail will execute your Artisan commands within your application's Docker containers:
./vendor/bin/sail artisan list
Tinker (REPL)
Laravel Tinker is a powerful REPL for the Laravel framework, powered by the PsySH package.
Installation
All Laravel applications include Tinker by default. However, you may install Tinker using Composer if you have previously removed it from your application:
composer require laravel/tinker
Looking for hot reloading, multiline code editing, and autocompletion when interacting with your Laravel application? Check out Tinkerwell!
Usage
Tinker allows you to interact with your entire Laravel application on the command line, including your Eloquent models, jobs, events, and more. To enter the Tinker environment, run the tinker Artisan command:
php artisan tinker
You can publish Tinker's configuration file using the vendor:publish command:
php artisan vendor:publish --provider="Laravel\Tinker\TinkerServiceProvider"
The dispatch helper function and dispatch method on the Dispatchable class depends on garbage collection to place the job on the queue. Therefore, when using tinker, you should use Bus::dispatch or Queue::push to dispatch jobs.
Command Allow List
Tinker utilizes an "allow" list to determine which Artisan commands are allowed to be run within its shell. By default, you may run the clear-compiled, down, env, inspire, migrate, migrate:install, up, and optimize commands. If you would like to allow more commands you may add them to the commands array in your tinker.php configuration file:
'commands' => [
// App\Console\Commands\ExampleCommand::class,
],
Classes That Should Not Be Aliased
Typically, Tinker automatically aliases classes as you interact with them in Tinker. However, you may wish to never alias some classes. You may accomplish this by listing the classes in the dont_alias array of your tinker.php configuration file:
'dont_alias' => [
App\Models\User::class,
],
Writing Commands
In addition to the commands provided with Artisan, you may build your own custom commands. Commands are typically stored in the app/Console/Commands directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer.
Generating Commands
To create a new command, you may use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don't worry if this directory does not exist in your application - it will be created the first time you run the make:command Artisan command:
php artisan make:command SendEmails
Command Structure
After generating your command, you should define appropriate values for the signature and description properties of the class. These properties will be used when displaying your command on the list screen. The signature property also allows you to define your command's input expectations. The handle method will be called when your command is executed. You may place your command logic in this method.
Let's take a look at an example command. Note that we are able to request any dependencies we need via the command's handle method. The Laravel service container will automatically inject all dependencies that are type-hinted in this method's signature:
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;
class SendEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send a marketing email to a user';
/**
* Execute the console command.
*/
public function handle(DripEmailer $drip): void
{
$drip->send(User::find($this->argument('user')));
}
}
For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example above, note that we inject a service class to do the "heavy lifting" of sending the e-mails.
Exit Codes
If nothing is returned from the handle method and the command executes successfully, the command will exit with a 0 exit code, indicating success. However, the handle method may optionally return an integer to manually specify command's exit code:
$this->error('Something went wrong.');
return 1;
If you would like to "fail" the command from any method within the command, you may utilize the fail method. The fail method will immediately terminate execution of the command and return an exit code of 1:
$this->fail('Something went wrong.');
Closure Commands
Closure based commands provide an alternative to defining console commands as classes. In the same way that route closures are an alternative to controllers, think of command closures as an alternative to command classes.
Even though the routes/console.php file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your closure based console commands using the Artisan::command method. The command method accepts two arguments: the command signature and a closure which receives the command's arguments and options:
Artisan::command('mail:send {user}', function (string $user) {
$this->info("Sending email to: {$user}!");
});
The closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class.
Type-Hinting Dependencies
In addition to receiving your command's arguments and options, command closures may also type-hint additional dependencies that you would like resolved out of the service container:
use App\Models\User;
use App\Support\DripEmailer;
Artisan::command('mail:send {user}', function (DripEmailer $drip, string $user) {
$drip->send(User::find($user));
});
Closure Command Descriptions
When defining a closure based command, you may use the purpose method to add a description to the command. This description will be displayed when you run the php artisan list or php artisan help commands:
Artisan::command('mail:send {user}', function (string $user) {
// ...
})->purpose('Send a marketing email to a user');
Isolatable Commands
To utilize this feature, your application must be using the memcached, redis, dynamodb, database, file, or array cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.
Sometimes you may wish to ensure that only one instance of a command can run at a time. To accomplish this, you may implement the Illuminate\Contracts\Console\Isolatable interface on your command class:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;
class SendEmails extends Command implements Isolatable
{
// ...
}
When a command is marked as Isolatable, Laravel will automatically add an --isolated option to the command. When the command is invoked with that option, Laravel will ensure that no other instances of that command are already running. Laravel accomplishes this by attempting to acquire an atomic lock using your application's default cache driver. If other instances of the command are running, the command will not execute; however, the command will still exit with a successful exit status code:
php artisan mail:send 1 --isolated
If you would like to specify the exit status code that the command should return if it is not able to execute, you may provide the desired status code via the isolated option:
php artisan mail:send 1 --isolated=12
Lock ID
By default, Laravel will use the command's name to generate the string key that is used to acquire the atomic lock in your application's cache. However, you may customize this key by defining an isolatableId method on your Artisan command class, allowing you to integrate the command's arguments or options into the key:
/**
* Get the isolatable ID for the command.
*/
public function isolatableId(): string
{
return $this->argument('user');
}
Lock Expiration Time
By default, isolation locks expire after the command is finished. Or, if the command is interrupted and unable to finish, the lock will expire after one hour. However, you may adjust the lock expiration time by defining a isolationLockExpiresAt method on your command:
use DateTimeInterface;
use DateInterval;
/**
* Determine when an isolation lock expires for the command.
*/
public function isolationLockExpiresAt(): DateTimeInterface|DateInterval
{
return now()->addMinutes(5);
}
Defining Input Expectations
When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the signature property on your commands. The signature property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.
Arguments
All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: user:
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user}';
You may also make arguments optional or define default values for arguments:
// Optional argument...
'mail:send {user?}'
// Optional argument with default value...
'mail:send {user=foo}'
Options
Options, like arguments, are another form of user input. Options are prefixed by two hyphens (--) when they are provided via the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean "switch". Let's take a look at an example of this type of option:
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user} {--queue}';
In this example, the --queue switch may be specified when calling the Artisan command. If the --queue switch is passed, the value of the option will be true. Otherwise, the value will be false:
php artisan mail:send 1 --queue
Options With Values
Next, let's take a look at an option that expects a value. If the user must specify a value for an option, you should suffix the option name with a = sign:
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user} {--queue=}';