Ahsan
Ahsan

Reputation: 1084

How to get Artisan::call('command:name') output in a variable?

Is it possible to get $output as follows:

$output = Artisan::call('command:name');

I have tried many solutions in different posts but it didn't work on my Laravel 5.2.

Upvotes: 2

Views: 4295

Answers (2)

Bram Verstraten
Bram Verstraten

Reputation: 1557

You can call the output method on Artisan

Artisan::call('command:name');
$output = Artisan::output();

Make sure you are using one of the available output methods like $this->line('output'); in the actual Artisan command. More info in the docs.

Upvotes: 8

emiliopedrollo
emiliopedrollo

Reputation: 950

There are several ways to accomplish this, but as your are using such old version of Laravel maybe the best for your case is one that will not require a rewrite when you finally migrate to a newer version. Have you tried perhaps the vanilla PHP methods system, shell_exec and passthru?

  • system will return just the last line of the command on succes and FALSE on failure
  • shell_exec will return the entire output but without a way to fetch the output status code
  • passthru will not return any output instead it will output all on stdout. Although it can be put into a variable using output cache methods (i.e. ob_start and ob_get_contents)

In any case you should call those methods using as argument the CLI version of the command you wish to run:

$output = shell_exec("php artisan command:here");

P.S. If you by any chance have a user input that you want to pass as parameter to a artisan command, make sure you escape it with escapeshellcmd first.

Upvotes: 1

Related Questions