Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BindingResolutionException when using constructor params in Laravel 5 Command

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

like image 385
Joel Joel Binks Avatar asked Nov 01 '22 03:11

Joel Joel Binks


1 Answers

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

like image 117
Marcin Nabiałek Avatar answered Nov 09 '22 06:11

Marcin Nabiałek