Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do the type-hint 'automatic injection' custom class laravel

Below is the EmailNotifier Class

class EmailNotifier 
{
    public function notify()
    {
        echo 'Sending payment notification via email' ;
    }
}

Below is my AppServiceProvider

 class AppServiceProvider extends ServiceProvider
    {

        public function boot()
        {

        }

        public function register()
        {
           $this->app->make(App\EmailNotifier::class); // resolve the EmailNotifier Class
        }

    }

Below is billing class

class Billing
{

     protected $notifier;


     public function __construct(EmailNotifier  $notifier)
     {
         $this->notifier = $notifier;
     }

     public function pay()
     {
        // Process the bill payment
         $this->notifier->notify();
     }

}

and in my controller I did

  $data = new Billing(1); 

As you can see I already resolve the EmailNotifier Class at the AppServiceProvider Class but when I call that like the code above, it throws an error said 'must be an instance of EmailNotifier'

and based on the laravel documentation, it's stated that :

you may "type-hint" the dependency in the constructor of a class that is resolved by the container (for the automatic injection)

how do I achieve automatic injection for the type-hint in laravel ?

like image 540
Bathulah Mahir Avatar asked Nov 30 '25 14:11

Bathulah Mahir


1 Answers

Use $data = resolve(Billing::class); instead of $data = new Billing(1); and you can remove $this->app->make(App\EmailNotifier::class); // resolve the EmailNotifier Class from service provider's register method.

like image 111
DoeJane Avatar answered Dec 02 '25 05:12

DoeJane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!