I get an error:
Type error: Too few arguments
I thought Laravel do some magic to if arguments is not fully passed?
For example:
In the Controller I have:
public function create(CreateRequest $request)
{
return $this->todoService->createList($request);
}
In the todoService
class:
use App\Plan
class todoService {
public function createList($request, Plan $plan)
{
//
}
}
As you can see I did not pass Plan
class object. Do I have to bind or something?
If you are calling createList() by yourself so you will need to pass both parameters by yourself. You can bind something with Plan but still if you will call something not Laravel, then you will be responsible to pass that function parameters.
This type hinting only works if Laravel is calling that function. So you need to call these functions through Laravel.
If you are trying to automatically injecting in a class's constructor, you can simply do this:
$service = $this->app->make('App\Plan\todoservice');
or
$service = App::make('App\Plan\todoservice');
or
$service = resolve('App\Plan\todoservice');
But this will only work for Constructors. Please note that you can also provide parameters as next arguments of make()
or resolve()
function.
In fact, different methods can also be called that way.
You can simply do:
$service = App::make('App\Plan\todoservice');
$container->call([$service, 'createList'], ['request' => $request] );
Here $container
is object of Illuminate\Contracts\Container\Container
.
You have to bind
classes only if they depend on interfaces. If you specify particular class, reflection will do the job for you. documentation
The only way this will work, is to set the default value of second parameter. In any other situation, syntax exception will be thrown.
use App\Plan
class todoService
{
public function createList($request, Plan $plan = null)
{
//
}
}
public function create(CreateRequest $request)
{
return $this->todoService->createList($request);
}
It will work, but will that make any sense?
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