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.
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();
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With