Laravel 5 target is not instantiable
Looks like you've spelled the namespace wrong when binding, used App\Contacts instead of App\Contracts. Should be:
$this->app->bind('App\Contracts\Messenger', 'App\Services\DailyMessenger');
Hak
Updated on June 26, 2022Comments
-
Hak almost 2 years
Multiple questions already asked about this topic, but I still have this problem and I don't have a clue on what the problem is.
I want to achieve that I can instantiate an interface instead of an implementation.
I'm using Laravel 5, this is the code/structure:
In app, I have created a Contracts folder. In this folder I have Messenger.php:
Messenger.php
<?php namespace App\Contracts; interface Messenger { public function goodmorning($name); }
In app/Services I have DailyMessenger.php
<?php namespace App\Services; use App\Contracts\Messenger; class DailyMessenger implements Messenger { public function goodmorning($name) { return 'Goodmorning '. $name; } }
Now I want to instantiate the interface in my controller:
public function __construct(Messenger $messenger) { $this->messenger = $messenger; }
Now, if I follow the documentation on the Laravel website I should only have to register this in the service container, which I do in the existing AppServiceProvider.php
public function register() { $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'App\Services\Registrar' ); $this->app->bind('App\Contacts\Messenger', 'App\Services\DailyMessenger'); }
If I visit appropriate route that maps to the controller I get the error:
BindingResolutionException in Container.php line 785: Target [App\Contracts\Messenger] is not instantiable.
I think I have followed the Laravel docs precisely but what am I missing? Thanks in advance :-)