The command-line interface (CLI) can be a powerful tool for developers. You can use it as part of your development workflow to add new features to your application and to perform tasks in a production environment. Laravel allows you to create "Artisan commands" to add bespoke functionality to your application. It also provides a Process
facade that you can use to run OS (operating system) processes from your Laravel application to perform tasks such as running custom shell scripts.
In this article, we'll explore what Artisan commands are and provide tips and tricks for creating and testing them. We'll also look at how to run operating system (OS) processes from your Laravel application and test they are called correctly.
What are Artisan commands?
Artisan commands can be run from the CLI to perform many tasks on a Laravel app. They can allow a more streamlined development process and be used to perform tasks in a production environment.
As a Laravel developer, you'll have likely already used some built-in Artisan commands, such as php artisan make:model
, php artisan migrate
, and php artisan down
.
For example, some Artisan commands can be used as part of the development process, such as php artisan make:model
and php artisan make:controller
. Typically, these wouldn't be run in a production environment and are used purely to speed up the development process by creating boilerplate files.
Some Artisan commands can be used to perform tasks in a production environment, such as php artisan migrate
and php artisan down
. These are used to perform tasks, such as running database migrations and taking your application offline while you perform maintenance or roll out an update.
Thus, Artisan commands can be used to perform a variety of tasks and can be used in both development and production environments.
Creating your own Artisan commands
Now that we have a better understanding of what Artisan commands are, let's look at how we can create our own.
Getting input from users
To give some examples of what we can do with Artisan commands, let's take a look at a common use-case for them that you may across in your own projects: creating a new super admin in the database. In this example, we need the following pieces of information to create a new super admin:
- Name
- Email address
- Password
Let's create the command to do this. We'll call the command CreateSuperAdmin
and create it by running the following command:
1php artisan make:command CreateSuperAdmin
This command will create a new app/Console/Commands/CreateSuperAdmin.php
file. We'll assume that we have access to a createSuperAdmin
method in a UserService
class. For the purposes of this article, we don't need to know what it does or how it works since we're focused on how the commands work.
The command class created by the make:command
command will look something like this:
app/Console/Commands/CreateSuperAdmin.php
1namespace App\Console\Commands;23use Illuminate\Console\Command;45class CreateSuperAdmin extends Command6{7 /**8 * The name and signature of the console command.9 *10 * @var string11 */12 protected $signature = 'app:create-super-admin';1314 /**15 * The console command description.16 *17 * @var string18 */19 protected $description = 'Command description';2021 /**22 * Execute the console command.23 */24 public function handle(): void25 {26 //27 }28}
Now we want to add our arguments to the command so that we can accept the name, email, and password for each new user. We can do this by updating the signature
property of the command class. The signature
property is used to define the name of the command, the arguments, and the options that the command accepts.
The signature
property should look something like this:
1protected $signature = 'app:create-super-admin {--email=} {--password=} {--name=}';
We may also want to add an option to the command to allow the user to specify whether an email should be sent to confirm the account. By default, we'll assume the user shouldn't be sent the email. To add this option to the code, we can update the signature
property to look like this:
1protected $signature = 'app:create-super-admin {--email=} {--password=} {--name=} {--send-email}';
It's important to also update the command's description
property to describe what it does. This will be displayed when the user runs the php artisan list
or php artisan help
commands.
Now that we have our options configured to accept input, we can pass these options to our createSuperAdmin
method. Let's take a look at what our command class will look like now:
app/Console/Commands/CreateSuperAdmin.php
1namespace App\Console\Commands;23use App\Services\UserService;4use Illuminate\Console\Command;56class CreateSuperAdmin extends Command7{8 /**9 * The name and signature of the console command.10 *11 * @var string12 */13 protected $signature = 'app:create-super-admin {--email=} {--password=} {--name=} {--send-email}';1415 /**16 * The console command description.17 *18 * @var string19 */20 protected $description = 'Store a new super admin in the database';2122 /**23 * Execute the console command.24 */25 public function handle(UserService $userService): int26 {27 $userService->createSuperAdmin(28 email: $this->option('email'),29 password: $this->option('password'),30 name: $this->option('name'),31 sendEmail: $this->option('send-email'),32 );3334 $this->components->info('Super admin created successfully!');3536 return self::SUCCESS;37 }38}
Our command should now be ready to run. We can run it using the following command:
1php artisan app:create-super-admin --email="hello@example.com" --name="John Doe" --password="password" --send-email
If we wanted to take this a step further, we may also want to add questions to the command so that the user can be prompted to enter the information if they don't provide it as an argument or option. This can provide a friendly user experience for developers, especially if they are new to using the command or if it has several arguments and options.
If we wanted to update our command to use questions, our command may now look something like this:
app/Console/Commands/CreateSuperAdmin.php
1namespace App\Console\Commands;23use App\Services\UserService;4use Illuminate\Console\Command;56class CreateSuperAdmin extends Command7{8 /**9 * The name and signature of the console command.10 *11 * @var string12 */13 protected $signature = 'app:create-super-admin {--email=} {--password=} {--name=} {--send-email}';1415 /**16 * The console command description.17 *18 * @var string19 */20 protected $description = 'Store a new super admin in the database';2122 /**23 * Execute the console command.24 */25 public function handle(UserService $userService): int26 {27 $userService->createSuperAdmin(28 email: $this->getInput('email'),29 password: $this->getInput('password'),30 name: $this->getInput('name'),31 sendEmail: $this->getInput('send-email'),32 );3334 $this->components->info('Super admin created successfully!');3536 return self::SUCCESS;37 }3839 public function getInput(string $inputKey): string40 {41 return match($inputKey) {42 'email' => $this->option('email') ?? $this->ask('Email'),43 'password' => $this->option('password') ?? $this->secret('Password'),44 'name' => $this->option('name') ?? $this->ask('Name'),45 'send-email' => $this->option('send-email') === true46 ? $this->option('send-email')47 : $this->confirm('Send email?'),48 default => null,49 };50 }51}
As you can see, we've added a new getInput
method to the command class. Within this method, we're checking whether an argument has been passed to the command. If it hasn't, we prompt the user for input. You may have also noticed that we've used the secret
method for getting the new password. This method is used so that we can hide the password from the terminal output. If we didn't use the secret
method, the password would be displayed in the terminal output. Similarly, we've also used the confirm
method for determining whether to send an email to the new user. This will prompt the user with a yes
or no
question, so it's a good way to get a Boolean value from the user rather than using the ask
method.
Running the command with only the email
argument would result in the following output:
1❯ php artisan app:create-super-admin --email="hello@example.com" 2 3Password: 4> 5 6Name: 7> Joe Smith 8 9Send email? (yes/no) [no]:10> yes
Anticipating input
If you're building a command for the user and providing multiple options to choose from a known dataset (e.g., rows in the database), you may sometimes want to anticipate the user's input. By doing this, it can suggest autocompleting options for the user to choose from.
For example, let's imagine that you have a command that can be used to create a new user and allows you to specify the user's role. You may want to anticipate the possible roles from which the user may choose. You can do this by using the anticipate
method:
1$roles = [2 'super-admin',3 'admin',4 'manager',5 'user',6];7 8$role = $this->anticipate('What is the role of the new user?', $roles);
When the user is prompted to choose the role, the command will try to autocomplete the field. For instance, if the user started typing sup
, the command would suggest er-admin
as the autocomplete.
Running the command would result in the following output:
1What is the role of the new user?:2> super-admin
It's important to remember that the anticipate
method is only providing a hint to the user, so they can still enter any value they'd like. Therefore, all input from the method must still be validated to ensure it can be used.
Multiple arguments and choice inputs
There may be times when you're building an Artisan command and want to enable users to enter multiple options from a list. If you've used Laravel Sail, you'll have already used this feature when you run the php artisan sail:install
command and are asked to choose the various services you want to install.
You can allow multiple inputs to be passed as arguments to the command. For example, if we wanted to create a command that can be used to install some services for our local development environment, we could allow the user to pass multiple services as arguments to the command:
1protected $signature = 'app:install-services {services?*}';
We could now call this command like so to install the mysql
and redis
services:
1php artisan app:install-services mysql redis
Within our Artisan command, $this->argument('services')
would return an array containing two items: mysql
and redis
.
We could also add this functionality to our command to display the options to the user if they don't provide any arguments by using the choice
method:
1$installableServices = [ 2 'mysql', 3 'redis', 4 'mailpit', 5]; 6 7$services = $this->choice( 8 question: 'Which services do you want to install?', 9 choices: $installableServices,10 multiple: true,11);
Running this command without any arguments would now display the following output:
1Which services do you want to install?:2 [0] mysql3 [1] redis4 [2] mailpit5> mysql,redis
Using the choice
method, we can allow the user to select multiple options from a list. The method provides auto-completion for the user, similar to the anticipate
method. It also comes in handy because it will only allow the user to select options from the list. If the user tries to enter an option that isn't on the list, they'll be prompted to try again. Hence, it can act as a form of validation for your users' input.
Input validation
Similar to how you would validate the input for an HTTP request, you may also want to validate the input of your Artisan commands. By doing this, you can ensure that the input is correct and can be passed to other parts of your application's code.
Let's take a look at a possible way to validate the input. We'll start by reviewing the code, and then I'll break it down afterwards.
To validate your input, you could do something like so:
app/Console/Commands/CreateSuperAdmin.php
1namespace App\Console\Commands;23use App\Services\UserService;4use Illuminate\Console\Command;5use Illuminate\Support\Facades\Validator;6use Illuminate\Support\MessageBag;7use InvalidArgumentException;89class CreateSuperAdmin extends Command10{11 /**12 * The name and signature of the console command.13 *14 * @var string15 */16 protected $signature = 'app:create-super-admin {--email=} {--password=} {--name=} {--send-email}';1718 /**19 * The console command description.20 *21 * @var string22 */23 protected $description = 'Store a new super admin in the database';2425 private bool $inputIsValid = true;2627 /**28 * Execute the console command.29 */30 public function handle(UserService $userService): int31 {32 $input = $this->validateInput();3334 if (!$this->inputIsValid) {35 return self::FAILURE;36 }3738 $userService->createSuperAdmin(39 email: $input['email'],40 password: $input['password'],41 name: $input['name'],42 sendEmail: $input['send-email'],43 );4445 $this->components->info('Super admin created successfully!');4647 return self::SUCCESS;48 }4950 /**51 * Validate and return all the input from the command. If any of the input52 * was invalid, an InvalidArgumentException will be thrown. We catch this53 * and report it so it's still logged or sent to a bug-tracking system.54 * But we don't display it to the console. Only the validation error55 * messages will be displayed in the console.56 *57 * @return array58 */59 private function validateInput(): array60 {61 $input = [];6263 try {64 foreach (array_keys($this->rules()) as $inputKey) {65 $input[$inputKey] = $this->validated($inputKey);66 }67 } catch (InvalidArgumentException $e) {68 $this->inputIsValid = false;6970 report($e);71 }7273 return $input;74 }7576 /**77 * Validate the input and then return it. If the input is invalid, we will78 * display the validation messages and then throw an exception.79 *80 * @param string $inputKey81 * @return string82 */83 private function validated(string $inputKey): string84 {85 $input = $this->getInput($inputKey);8687 $validator = Validator::make(88 data: [$inputKey => $input],89 rules: [$inputKey => $this->rules()[$inputKey]]90 );9192 if ($validator->passes()) {93 return $input;94 }9596 $this->handleInvalidData($validator->errors());97 }9899 /**100 * Loop through each of the error messages and output them to the console.101 * Then throw an exception so we can prevent the rest of the command102 * from running. We will catch this in the "validateInput" method.103 *104 * @param MessageBag $errors105 * @return void106 */107 private function handleInvalidData(MessageBag $errors): void108 {109 foreach ($errors->all() as $error) {110 $this->components->error($error);111 }112113 throw new InvalidArgumentException();114 }115116 /**117 * Define the rules used to validate the input.118 *119 * @return array<string,string>120 */121 private function rules(): array122 {123 return [124 'email' => 'required|email',125 'password' => 'required|min:8',126 'name' => 'required',127 'send-email' => 'boolean',128 ];129 }130131 /**132 * Attempt to get the input from the command options. If the input wasn't passed133 * to the command, ask the user for the input.134 *135 * @param string $inputKey136 * @return string|null137 */138 private function getInput(string $inputKey): ?string139 {140 return match($inputKey) {141 'email' => $this->option('email') ?? $this->ask('Email'),142 'password' => $this->option('password') ?? $this->secret('Password'),143 'name' => $this->option('name') ?? $this->ask('Name'),144 'send-email' => $this->option('send-email') === true145 ? $this->option('send-email')146 : $this->confirm('Send email?'),147 default => null,148 };149 }150}
Let's break down the above code.
First, we're calling a validateInput
method before we try to do anything with the input. This method loops through every input key that we've specified in our rules
method and calls the validated
method. The array returned from the validateInput
method will only contain validated data.
If any of the input is invalid, the necessary error messages will be displayed on the page. You may have noticed that we're also catching any InvalidArgumentException
exceptions thrown. This is done so that we can still log or send the exception to a bug-tracking system, but without displaying the exception message in the console. Thus, we can keep the console output neat by only showing the validation error messages.
Running the above code and providing an invalid email address will result in the following output:
1❯ php artisan app:create-super-admin23Email:4> INVALID56ERROR The email field must be a valid email address.
Hiding commands from the list
Depending on the type of command you're building, you may want to hide it from the php artisan list
command that displays all your app's available commands. This is useful if you're building a command that is only intended to run once, such as an installation command for a package.
To hide a command from the list, you can use the setHidden
property to set the value the command's hidden
property to true
. For example, if you're building an installation command as part of a package that publishes some assets, you may want to check whether those assets already exist in the filesystem. If they do, you can probably assume that the command has already been run once and doesn't need to be displayed in the list
command output.
Let's take a look at how we can do this. We'll imagine that our package publishes a my-new-package.php
config file at the time of installation. If this file exists, we'll hide the command from the list. Our command's code may look something like this:
app/Console/Commands/PackageInstall.php
1namespace App\Console\Commands;23use Illuminate\Console\Command;45class PackageInstall extends Command6{7 protected $signature = 'app:package-install';89 protected $description = 'Install the package and publish the assets';1011 public function __construct()12 {13 parent::__construct();1415 if (file_exists(config_path('my-new-package.php'))) {16 $this->setHidden();17 }18 }1920 public function handle()21 {22 // Run the command here as usual...23 }24}
It's worth noting that hiding a command doesn't stop the command from being able to be run. If someone knows the name of the command, they can still run it.
Command help
When building your commands, it's crucial to use obvious names for your arguments and options. This will make it easier for other developers to understand what the command does and how to use it.
However, there may be times when you want to provide additional help information so they can be displayed in the console by running the php artisan help
command.
For instance, if we wanted to take our CreateSuperAdmin
example from earlier in this guide, we could update the signature to the following:
1protected $signature = 'app:create-super-admin2 {--email= : The email address of the new user}3 {--password= : The password of the new user}4 {--name= : The name of the new user}5 {--send-email : Send a welcome email after creating the user}';
Now if we were to run php artisan help app:create-super-admin
, we would see the following output:
1❯ php artisan help app:create-super-admin 2Description: 3 Store a new super admin in the database 4 5Usage: 6 app:create-super-admin [options] 7 8Options: 9 --email[=EMAIL] The email address of the new user10 --password[=PASSWORD] The password of the new user11 --name[=NAME] The name of the new user12 --send-email Send a welcome email after creating the user13 -h, --help Display help for the given command. When no command is given display help for the list command14 -q, --quiet Do not output any message15 -V, --version Display this application version16 --ansi|--no-ansi Force (or disable --no-ansi) ANSI output17 -n, --no-interaction Do not ask any interactive question18 --env[=ENV] The environment the command should run under19 -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Automate tasks using the scheduler
Artisan commands also provide a way to automate tasks in your application.
For example, let's say that on the first day of every month, you want to build a PDF report for your users' activity from the previous month and email it to them. To automate this process, you could create a custom Artisan command and add it to your app's "scheduler". Assuming you had a scheduler set up on your server, this command would run automatically on the first day of each month and send the report to your users.
For the purposes of this article, we won't be covering how to set up a scheduler on your server. However, if you're interested in learning more about how to do this, you can check out the Laravel documentation. In its most basic terms, though, the scheduler is a cron job that runs on your server and is called once a minute. The cron job runs the following command:
1php /path/to/artisan schedule:run >> /dev/null 2>&1
It's essentially just calling the php artisan schedule:run
command for your project, which allows Laravel to handle whether the scheduled commands are ready to be run. The >> /dev/null
part of the command is redirecting the output of the command to /dev/null
which discards it, so it's not displayed. The 2>&1
part of the command is redirecting the error output of the command to the standard output. This is used so that any errors occurring when the command is run are also discarded.
Now, let's take a look at how to add a command to the scheduler in Laravel.
Let's imagine we want to implement our example from above and email our users on the first day of each month. To do this, we'll need to create a SendMonthlyReport
Artisan command:
app/Console/Commands/SendMonthlyReport.php
1namespace App\Console\Commands;23use Illuminate\Console\Command;45class SendMonthlyReport extends Command6{7 protected $signature = 'app:send-monthly-report';89 protected $description = 'Send monthly report to each user';1011 public function handle(): void12 {13 // Send the monthly reports here...14 }15}
After creating your command, we can then add it to your app's scheduler. To do this, we'll need to register it in the schedule
method of the app/Console/Kernel.php
file. Your Kernel
class may look something like this:
app/Console/Kernel.php
1namespace App\Console;23use App\Console\Commands\SendMonthlyReport;4use Illuminate\Console\Scheduling\Schedule;5use Illuminate\Foundation\Console\Kernel as ConsoleKernel;67class Kernel extends ConsoleKernel8{9 /**10 * Define the application's command schedule.11 */12 protected function schedule(Schedule $schedule): void13 {14 $schedule->command('app:send-monthly-report')->monthly();15 }1617 // ...1819}
If your scheduler is set up correctly on your server, this command should now automatically run at the beginning of each month.
A top tip when building automated commands like this is to add the functionality to pass arguments and options to the command. Sometimes, the command may fail when it's run automatically. For example, a user might not receive their monthly report, so by adding the options and arguments, you could manually rerun the command just for one user rather than everyone in the system. Although you may feel you don't need this functionality, it is something that has always come in handy with projects I've worked on.
Testing your Artisan commands
Like any other piece of code you write, it's important you test your Artisan commands. This is particularly true if you're going to be using them in a production environment or to automate tasks via the scheduler.
Asserting output from commands
Typically, the easiest parts of your command to test are that they were run successfully and that they output the expected text.
Let's imagine that we have the following example command we want to test:
app/Console/Commands/CreateUser.php
1namespace App\Console\Commands;23use App\Services\UserService;4use Illuminate\Console\Command;56class CreateUser extends Command7{8 protected $signature = 'app:create-user {email} {--role=}';910 protected $description = 'Create a new user';1112 public function handle(UserService $userService): int13 {14 $userService->createUser(15 email: $this->argument('email'),16 role: $this->option('role'),17 );1819 $this->info('User created successfully!');2021 return self::SUCCESS;22 }23}
If we wanted to test that it was run successfully and that it outputs the expected text, we could do the following:
tests/Feature/Console/Commands/CreateUserTest.php
1namespace Tests\Feature\Console\Commands;23use Tests\TestCase;45class CreateUserTest extends TestCase6{7 /** @test */8 public function user_can_be_created(): void9 {10 $this->artisan('app:create-user', [11 'email' => 'hello@example.com',12 '--role' => 'super-admin'13 ])14 ->expectsOutput('User created successfully!')15 ->assertSuccessful();1617 // Run extra assertions to check the user was created with the correct role...18 }19}
Asserting questions are asked
If your application asks the user a question, you will need to specify the answer to the question in your test. This can be done by using the expectsQuestion
method.
For example, let's imagine we want to test the following command:
1protected $signature = 'app:create-user {email}'; 2 3protected $description = 'Create a new user'; 4 5public function handle(UserService $userService): int 6{ 7 $roles = [ 8 'super-admin', 9 'admin',10 'manager',11 'user',12 ];13 14 $role = $this->choice('What is the role of the new user?', $roles);15 16 if (!in_array($role, $roles, true)) {17 $this->error('The role is invalid!');18 19 return self::FAILURE;20 }21 22 $userService->createUser(23 email: $this->argument('email'),24 role: $role,25 );26 27 $this->info('User created successfully!');28 29 return self::SUCCESS;30}
To test this command, we could do the following:
1/** @test */ 2public function user_can_be_created_with_choice_for_role(): void 3{ 4 $this->artisan('app:create-user', [ 5 'email' => 'hello@example.com', 6 ]) 7 ->expectsQuestion('What is the role of the new user?', 'super-admin') 8 ->expectsOutput('User created successfully!') 9 ->assertSuccessful();10 11 // Run extra assertions to check the user was created with the correct role...12}13 14/** @test */15public function error_is_returned_if_the_role_is_invalid(): void16{17 $this->artisan('app:create-user', [18 'email' => 'hello@example.com',19 ])20 ->expectsQuestion('What is the role of the new user?', 'INVALID')21 ->expectsOutput('The role is invalid!')22 ->assertFailed();23 24 // Run extra assertions to check the user wasn't created...25}
As you can see in the code above, we have one test to ensure the user is created successfully and another test to ensure that an error is returned if the role is invalid.
Running OS processes in Laravel
So far, we've looked at how you can run interact with your Laravel application by running commands from the operating system. However, there may be times when you want to do the opposite and run commands on the operating system from your Laravel application.
This can be useful, for example, when running custom shell scripts, antivirus scans, or file converters.
Let's take a look at how we can add this functionality to our application by using the Process
facade that was added in Laravel 10. We'll cover several of the features that you'd be most likely to use in your application. However, if you want to see all the available methods, you can check out the Laravel documentation.
Running processes
To run a command on the operating system, you can use the run
method on the Process
facade. Let's imagine that we have a shell script called install.sh
in the root directory of our project. We can run this script from our code:
1use Illuminate\Support\Facades\Process;2 3$process = Process::path(base_path())->run('./install.sh');4$output = $process->output();
To provide additional context, we may want to run this script from the handle
method of an Artisan command that does several things (e.g., reading from the database or making API calls). We could call the shell script from our command:
1use Illuminate\Console\Command; 2use Illuminate\Support\Facades\Process; 3 4class RunInstallShellScript extends Command 5{ 6 /** 7 * The name and signature of the console command. 8 * 9 * @var string10 */11 protected $signature = 'app:run-install-shell-script';12 13 /**14 * The console command description.15 *16 * @var string17 */18 protected $description = 'Install the package and publish the assets';19 20 /**21 * Execute the console command.22 */23 public function handle(): void24 {25 $this->info('Starting installation...');26 27 $process = Process::path(base_path())->run('./install.sh');28 29 $this->info($process->output());30 31 // Make calls to API here...32 33 // Publish assets here...34 35 // Add new rows to the database here...36 37 $this->info('Installation complete!');38 }39}
You may also notice that we've grabbed the output using the output
method so that we can handle it in our Laravel application. For example, if the process was being run via an HTTP request, we may want to display the output on the page.
The commands typically have two types of output: standard output and error output. If we wanted to get any error output from the process, we'd need to use the errorOutput
method instead.
Running the process from another directory
By default, the Process
facade will run the command in the same working directory as the PHP file that's being run. Typically, this means if you are running the process using an Artisan command, the process will be run in the root directory of your project because that's where the artisan
file is located. However, if the process is being run from an HTTP controller, the process will be run in the public
directory of your project because that's the entry point for the web server.
Therefore, if you can run the process from both the console and the web, not explicitly specifying the working directory may result in unexpected behavior and errors. One way to tackle this problem is to ensure you always use the path
method where possible. This will ensure that the process is always run in the expected directory.
For example, let's imagine that we have a shell script called custom-script.sh
in a scripts/custom
directory in our project. To run this script, we could do the following:
1use Illuminate\Support\Facades\Process;2 3$process = Process::path(base_path('/scripts/custom'))->run('./install.sh');4$output = $process->output();
Specifying the process timeout
By default, the Process
facade will allow processes to be run for a maximum of 60 seconds before it times out. This is to prevent processes from running indefinitely (e.g., if they get stuck in an infinite loop).
However, if you want to run a process that may take longer than the default timeout, you can specify a custom timeout in seconds by using the timeout
method. For example, let's imagine that we want to run a process that may take up to 5 minutes (300 seconds) to complete:
1use Illuminate\Support\Facades\Process;2 3$process = Process::timeout(300)->run('./install.sh');4$output = $process->output();
Getting the output in real time
Depending on the process you're executing, you may prefer to output the text from the process as it's running rather than waiting for the process to finish. You might want to do this if you have a long-running script (e.g., an installation script) where you want to see the steps the script is going through.
To do this, you can pass a closure as the second parameter of the run
method to determine what to do with the output as it's received. For example, let's imagine that we have a shell script called install.sh
and want to see the output in real-time rather than waiting until it's finished. We could run the script like so:
1use Illuminate\Support\Facades\Process;2 3$process = Process::run('./install.sh', function (string $type, string $output): void {4 $type === 'out' ? $this->line($output) : $this->error($output);5});
Running processes asynchronously
There may be times when you want to run a process and carry on running other code while it's running rather than waiting until it's complete. For example, you may want to run an installation script and write to the database or make some API calls while the installation is ongoing.
To do this, you can use the start
method. Let's take a look at an example of how we might do this. Let's imagine that we have a shell script called install.sh
and want to run some other installation steps while we wait for the shell script to finish running:
1use Illuminate\Support\Facades\Process; 2 3public function handle(): void 4{ 5 $this->info('Starting installation...'); 6 7 $extraCodeHasBeenRun = false; 8 9 $process = Process::start('./install.sh');10 11 while ($process->running()) {12 if (!$extraCodeHasBeenRun) {13 $extraCodeHasBeenRun = true;14 15 $this->runExtraCode();16 }17 }18 19 $result = $process->wait();20 21 $this->info($process->output());22 23 $this->info('Installation complete!');24}25 26private function runExtraCode(): void27{28 // Make calls to API here...29 30 // Publish assets here...31 32 // Add new rows to the database here...33}
As you may have noticed, we're checking in the while
loop that we haven't already started running the extra code. We do this because we don't want to run the extra code multiple times. We only want to run it once while the process is running.
After the process has finished running, we can get the result of the process (using the output
method) and output it to the console.
Running processes concurrently
There may be times when you want to run multiple commands concurrently. For example, you may want to do this if you have a script that converts a file from one format to another. If you want to convert multiple files at once in bulk (and the script doesn't support multiple files), you may want to run the script for each file concurrently.
This is beneficial because you don't need to run the script for each file sequentially. For instance, if a script took five seconds to run for each file, and you had 3 files to convert, it would take fifteen seconds to run sequentially. However, if you ran the script concurrently, it would only take five seconds to run.
To do this you can use the concurrently
method. Let's take a look at an example of how to use it.
We'll imagine that we want to run a convert.sh
shell script for three files in a directory. For the purpose of this example, we'll hardcode these filenames. However, in a real-world scenario, you'd likely get these filenames dynamically from the filesystem, database, or request.
If we run the scripts sequentially, our code may look something like this:
1// 15 seconds to run...2 3$firstOutput = Process::path(base_path())->run('./convert.sh file-1.png');4$secondOutput = Process::path(base_path())->run('./convert.sh file-1.png');5$thirdOutput = Process::path(base_path())->run('./convert.sh file-1.png');
However, if we run the scripts concurrently, our code may look something like this:
1// 5 seconds to run... 2 3$commands = Process::concurrently(function (Pool $pool) { 4 $pool->path(base_path())->command('./convert.sh file-1.png'); 5 $pool->path(base_path())->command('./convert.sh file-2.png'); 6 $pool->path(base_path())->command('./convert.sh file-3.png'); 7}); 8 9foreach ($commands->collect() as $command) {10 $this->info($command->output());11}
Testing OS processes
Like Artisan commands, you can also test that your OS processes are executed as expected. Let's take a look at some common things you may want to test.
To get started with testing our processes, let's imagine that we have a web route in our application that accepts a file and converts it to a different format. If the file passed is an image, we'll convert the file using a convert-image.sh
script. If the file is a video, we'll convert it using convert-video.sh
. We'll assume that we have an isImage
method in our controller that will return true
if the file is an image and false
if it's a video.
For the purposes of this example, we're not going to worry about any validation or HTTP testing. We'll focus solely on testing the process. However, in a real-life project, you would want to ensure that your test covers all the possible scenarios.
We'll imagine that our controller can be reached via a POST request to /file/convert
(with the route named file.convert
) and that it looks something this:
app/Http/Controllers/ConvertFileController.php
1namespace App\Http\Controllers;23use Illuminate\Http\Request;4use Illuminate\Http\UploadedFile;5use Illuminate\Support\Facades\Process;6use Illuminate\Support\Facades\Storage;7use Illuminate\Support\Str;89class ConvertFileController extends Controller10{11 /**12 * Handle the incoming request.13 */14 public function __invoke(Request $request)15 {16 // Temporarily the file so it can be converted.17 $tempFilePath = 'tmp/'.Str::random();1819 Storage::put(20 $tempFilePath,21 $request->file('uploaded_file')22 );2324 // Determine which command to run.25 $command = $this->isImage($request->file('uploaded_file'))26 ? 'convert-image.sh'27 : 'convert-video.sh';2829 $command .= ' '.$tempFilePath;3031 // The conversion command.32 $process = Process::timeout(30)33 ->path(base_path())34 ->run($command);3536 // If the process fails, report the error.37 if ($process->failed()) {38 // Report the error here to the logs or bug tracking system...3940 return response()->json([41 'message' => 'Something went wrong!',42 ], 500);43 }4445 return response()->json([46 'message' => 'File converted successfully!',47 'path' => trim($process->output()),48 ]);49 }5051 // ...52}
To test that the processes are correctly dispatched, we may want to write the following tests:
1namespace Tests\Feature\Http\Controllers; 2 3use Illuminate\Http\UploadedFile; 4use Illuminate\Process\PendingProcess; 5use Illuminate\Support\Facades\Process; 6use Illuminate\Support\Facades\Storage; 7use Illuminate\Support\Str; 8use Tests\TestCase; 9 10class ConvertFileControllerTest extends TestCase 11{ 12 public function setUp(): void 13 { 14 parent::setUp(); 15 16 Storage::fake(); 17 18 Process::preventStrayProcesses(); 19 20 // Determine how the random strings should be built. 21 // We do this so we can assert the correct command 22 // is run. 23 Str::createRandomStringsUsing(static fn (): string => 'random'); 24 } 25 26 /** @test */ 27 public function image_can_be_converted(): void 28 { 29 Process::fake([ 30 'convert-image.sh tmp/random' => Process::result( 31 output: 'tmp/converted.webp', 32 ) 33 ]); 34 35 $this->post(route('file.convert'), [ 36 'uploaded_file' => UploadedFile::fake()->image('dummy.png'), 37 ]) 38 ->assertOk() 39 ->assertExactJson([ 40 'message' => 'File converted successfully!', 41 'path' => 'tmp/converted.webp', 42 ]); 43 44 Process::assertRan(function (PendingProcess $process): bool { 45 return $process->command === 'convert-image.sh tmp/random' 46 && $process->path === base_path() 47 && $process->timeout === 30; 48 }); 49 } 50 51 /** @test */ 52 public function video_can_be_converted(): void 53 { 54 Process::fake([ 55 'convert-video.sh tmp/random' => Process::result( 56 output: 'tmp/converted.mp4', 57 ) 58 ]); 59 60 $this->post(route('file.convert'), [ 61 'uploaded_file' => UploadedFile::fake()->create('dummy.mp4'), 62 ]) 63 ->assertOk() 64 ->assertExactJson([ 65 'message' => 'File converted successfully!', 66 'path' => 'tmp/converted.mp4', 67 ]); 68 69 Process::assertRan(function (PendingProcess $process): bool { 70 return $process->command === 'convert-video.sh tmp/random' 71 && $process->path === base_path() 72 && $process->timeout === 30; 73 }); 74 } 75 76 /** @test */ 77 public function error_is_returned_if_the_file_cannot_be_converted(): void 78 { 79 Process::fake([ 80 'convert-video.sh tmp/random' => Process::result( 81 errorOutput: 'Something went wrong!', 82 exitCode: 1 // Error exit code 83 ) 84 ]); 85 86 $this->post(route('file.convert'), [ 87 'uploaded_file' => UploadedFile::fake()->create('dummy.mp4'), 88 ]) 89 ->assertStatus(500) 90 ->assertExactJson([ 91 'message' => 'Something went wrong!', 92 ]); 93 94 Process::assertRan(function (PendingProcess $process): bool { 95 return $process->command === 'convert-video.sh tmp/random' 96 && $process->path === base_path() 97 && $process->timeout === 30; 98 }); 99 }100}
The above tests will ensure the following:
- If a file is an image, only the
convert-image.sh
script is run. - If a file is a video, only the
convert-video.sh
script is run. - If the conversion script fails, an error is returned.
You may have noticed that we've used the preventStrayProcesses
method. This ensures that only the commands we have specified are run. If any other commands are run, the test will fail. This is handy for giving you confidence that the scripts aren't accidentally running any external processes on your system.
We've also explicitly tested that the commands are run with the expected path and timeout. This is to ensure that the commands are run with the correct settings.
Conclusion
Hopefully, this article has shown you how to create and test your own Artisan commands. It should have also shown you how to run OS processes from your Laravel application and test them. You should now be able to implement both of these features in your projects to add extra functionality to your applications.