I am making a command that is invoked via controller. When I do a simple example command and controller like this, it works:
//Controller
$command = new TestCommand();
$this->dispatch($command);
//Command
public $name;
public function __construct()
{
$this->name = 'hi';
}
public function handle(TestCommand $command)
{
dd($command->name);
}
When I invoke the command via the controller, I get 'hi' which is correct. But when I try to pass something through the constructor, I get the binding resolution exception:
//Controller
$command = new TestCommand('hi');
$this->dispatch($command);
//Command
public $name;
public function __construct($name)
{
$this->name = $name;
}
public function handle(TestCommand $command)
{
dd($command->name);
}
Why is this? What I did looks identical to what I found in the Laravel docs example, yet I get this exception:
BindingResolutionException in Container.php line 872: Unresolvable dependency resolving [Parameter #0 [ $name ]] in class App\Commands\TestCommand
This is because of dependency injection. If you used in your constructor object like User $user
or Guard $auth
Laravel would inject those objects to constructor so you had this properties set. But Laravel cannot inject simple type variables so you get this error.
You can also read on docs page:
Of course, the constructor allows you to pass any relevant objects to the command, while the handle method executes the command.
so it won't work for non-object paramters
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