Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Type error: Too few arguments?

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?

like image 820
I'll-Be-Back Avatar asked May 13 '17 22:05

I'll-Be-Back


2 Answers

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.

like image 189
Hafiz Avatar answered Nov 12 '22 05:11

Hafiz


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?

like image 38
wujt Avatar answered Nov 12 '22 05:11

wujt