Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Laravel 5 get command response

I think I understand the concept of command in Laravel, in that it's a good place to put reuseable code, that can be called from controllers and the like, but I have a query:

Can I return a value back to the calling method from a command? For example, I have a controller method which creates a user in Active Directory, for which there is a command to do this. If the AD server is unreachable, I want to return a response back to the calling controller method. Is this possible?

It only shows in the documentation how to call a command using dispatch(), but nothing as to whether it can return anything.

And if you cannot return a value, can someone explain the reasoning behind why you wouldn't want to return a value? I know that queued commands may take a while and wouldn't be appropriate to wait for a response, but for commands that should be executed immediately I don't see why you wouldn't want to return a value.

Any help or advice is appreciated.

like image 411
Phil Cross Avatar asked May 07 '15 14:05

Phil Cross

2 Answers

In the context of the command bus, yes you can return values on non-queued commands. In your command handler method, simply return what you want:

public function handle(){
    return 'foobar';

And save the result of your dispatch command to a variable:

 $my_command_result = $this->dispatch(
    new MyCommand();
like image 126
Patrick Stephan Avatar answered Oct 16 '22 06:10

Patrick Stephan

Commands are not for storing reusable code in controllers. Theyre getting renamed to jobs in 5.1 and their main purpose it to work as Cron Jobs. If you have a method to create a user and want to use it in many places, you could store it in the User model.

like image 1
Pawel Bieszczad Avatar answered Oct 16 '22 08:10

Pawel Bieszczad