Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Target [Interface] is not instantiable while building [Controller]

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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?

>Solution :

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,
],
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading