Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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();
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?