Diego Viniegra
Diego Viniegra

Reputation: 9

Laravel, get the returned value from call method

I'm writting some custom commands for laravel and I need to get the returned value from one command called from the other, for example:

class One extends Illuminate\Console\Command
{
  protected $signature = 'cmd:one';

  public function handle()
  {
    // call 'Two' and uses the api information to continue
    $returnedValue = $this->call('cmd:two');

    dd($returnedValue) // int(1) ?? it seems to show exit code
  }
}



class Two extends Illuminate\Console\Command
{
  protected $signature = 'cmd:two';

  public function handle()
  {
    // this command retrieves some api information needed to continue
    return $infoFromAPI;
  }
}

I also tried calling statically Artisan::call(...) with the same result.

I know there is an $output property but doc is not clear about how use it.

Upvotes: 0

Views: 4953

Answers (2)

Chris Richardson
Chris Richardson

Reputation: 325

In fact you can return just about anything you like from a command if you ignore all best practices. for instance instead of

return $myarray;

which gets filtered through the is_numeric filter you can just

print_r($myJsonArray);

and in your other command

ob_start();

//call other command

$return = ob_get_clean();

and that is how to do everything badly but, it will work.

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

Information returned from handle finally goes to this line:

return is_numeric($statusCode) ? (int) $statusCode : 0;

so if in command Two you return 2 then result $returnedValue will be 2 but if you return array or 'test' string it will be 0.

So In fact you cannot do it like this. Result of command has to be numeric, so you cannot return for example array and reuse it in another command. In fact I don't think there is much point to run another command. You should rather create service that will call the endpoint and return result and if you need those 2 command, then you can call this service in 2 command and get result or if you cannot do it, you should put result from some storage (database/cache) and then use result from this storage in command One

Upvotes: 2

Related Questions