Laravel – Registering a Decorator

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Laravel – Registering a Decorator on this date .

I am trying to implement Decorator Pattern in Laravel container for Mailer service. Following the syntax on this page, as well as official documentation.

I am registering the MailerDecorator in AppServiceProvider‘s (which is registered in app.php config) register method.

$this->app->extend(Mailer::class, function ($mailer) {
    return new MailerDecorator($mailer);
});

Unfortunately, the Decorator is not registered and the app is still using the old implementation.

Is there a way to debug the container? Am I missing something?

Thanks!

Answer

Laravel Mailer class is binded with an alias of mailer so you can try registering the Decorator using mailer alias instead of Mailer::class.

$this->app->extend('mailer', function ($mailer) {
    return new MailerDecorator($mailer);
});