Laravel: Programmatically Running Composer commands

Sam Ngu
Nov 17, 2020

Sometimes we just want to run composer command directly in our PHP code. But there seems to be no other easy solution other than exec() or shell_exec() … or is there?

Photo by Isaac Ibbott on Unsplash

It turns out there is a built-in Composer helper class in Laravel’s ecosystem! Yes, that’s right, it lives under the Illuminate\Support namespace. However, it doesn’t have a method to run arbitrary composer commands out of the box.

Let’s tweak it and add some new flavour! 😎

Let’s begin

We will create a new Composer class that inherits \Illuminate\Support\Composer.

Usage

Programatically install a package:

app()->make(\App\Composer::class)->run(['require', 'some-package']);

Updating packages:

app()->make(\App\Composer::class)->run(['update']);

Troubleshooting

If you see this:

The HOME or COMPOSER_HOME environment variable must be set for 
composer to run correctly

You will need to add COMPOSER_HOME (composer config directory) to the environmental variable.

See here for the documentation.

To solve this, you can either:

  1. Add COMPOSER_HOME to .env with the value of $HOME/.config/composer
  2. Supply a one-off environment variable to the run command.

Eg.

$this->getProcess($command)->run(function ($type, $data){
echo $data;
}, [
'COMPOSER_HOME' => '$HOME/.config/composer'
]);

References

--

--