Home > database >  Target [Interface] is not instantiable while building [Controller]
Target [Interface] is not instantiable while building [Controller]

Time:01-29

I'm working with Laravel 9 and I have a Controller like this:

use App\Repositories\HomeRepositoryInterface;

class HomeController extends Controller
{
    private $homeRespository;

    public function __construct(HomeRepositoryInterface $homeRepository)
    {
        $this->homeRespository = $homeRepository;
    }

    ...

And here is the HomeRepositoryInterface:

<?php
namespace App\Repositories;

interface HomeRepositoryInterface
{
    public function newest();
}

And this is the HomeRepository itself:

<?php
namespace App\Repositories;

use App\Models\Question;

class HomeRepository implements HomeRepositoryInterface
{
    public function newest()
    {
        return $ques = Question::orderBy('created_at', 'DESC')->paginate(10);
    }
}

But now I get this error:

Target [App\Repositories\HomeRepositoryInterface] is not instantiable while building [App\Http\Controllers\HomeController].

So what's going wrong here?

How can I solve this issue?

CodePudding user response:

It seems that you did not introduce the service container.

For this, it is better to create a service provider as shown below and introduce the repository class to the container.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Repositories\HomeRepositoryInterface;
use App\Repositories\HomeRepository;

class RepositoryServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        // Bind Interface and Repository class together
        $this->app->bind(HomeRepositoryInterface::class, HomeRepository::class);
    }
}

Next, you should introduce this service provider in the config/app.php file.

'providers' => [
    ...
    ...
    ...
    App\Providers\RepositoryServiceProvider::class,
],
  • Related