Piping system processes in Laravel
Running system processes in Laravel is a common thing that we all need at some point. For instance, you might want to run a composer install command or an npm install command.
Laravel provides an Illuminate\Support\Facades\Process facade to run system processes which is a wrapper around the Symfony\Component\Process\Process class. So, for example, if you want to run a composer install command, you can do it like so.
use Illuminate\Support\Facades\Process;
$result = Process::run('composer install');
$result->isSuccessful(); // true
But sometimes, you might want to pipe the output of one command to another. For example, you might want to run an ls -la command and pipe the output of it to the grep command to filter out the files that contain the word “php” in it.
Laravel now comes with a pipe method that allows you to pipe the output of one command to another. Here’s how we can use it for the above example.
use Illuminate\Support\Facades\Process;
$result = Process::pipe(function (Pipe $pipe) {
$pipe->command('ls -la');
$pipe->command('grep -i "php"');
});
// returns the output of the last command
$result->output();
/*
-rw-rw-r-- 1 amitmerchant amitmerchant 529 Apr 4 12:59 index.php
drwxrwxr-x 3 amitmerchant amitmerchant 4096 Sep 10 2022 php
drwxrwxr-x 7 amitmerchant amitmerchant 4096 Nov 15 18:20 php8-in-a-nutshell-book
*/
As you can see, we can use the pipe method to pipe the output of one command to another. The pipe method accepts a callback that receives an instance of the Pipe class. The Pipe class has a command method that accepts the command to be run.
The last command’s output is returned by the output method of the Process facade.
You can also pass an array of commands to the pipe method which will be run in sequence.
use Illuminate\Support\Facades\Process;
$result = Process::pipe([
'ls -la',
'grep -i "php"',
]);
$result->output();
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!