Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Laravel - Creating A Service Provider

Below is a very basic service provider that just registers a single service, the PhpMailerWrapper, as a singleton to the Laravel service container. If you need it to not be a singleton, you would just replace singleton with bind. In this case the PhpMailerWrapper is just a class that allows us to use PHPMailer to send emails with attachments easily.


 * Service provider for registering the php mailer wrapper.

namespace Programster\PhpMailerWrapper;

class PhpMailerWrapperServiceProvider extends \Illuminate\Support\ServiceProvider
    public function register()
        $this->app->singleton(PhpMailerWrapper::class, function() {
            return new PhpMailerWrapper(

The PhpMailerWrapper needs various configuration parameters in order to be created. You provide these to laravel by adding the following to /config/services.php file:

    'emailer' => [
        'smtp_host' => '',
        'aws_key' => env('AWS_KEY'),
        'aws_secret' => env('AWS_SECRET'),
        'protocol' => "tls",
        'from_email' => '',
        'from_name' => 'support',

To add the service provider to Laravel, you need to edit the config/app.php file and add it like so:

         * Package Service Providers...

Using The Service

Now when you need to use the PhpMailerWrapper object, you do either of the following in your controller:

class MyController extends Controller
    public function main(\Programster\PhpMailerWrapper\PhpMailerWrapper $emailer)

... or you can make use of the resolve method as shown here:

class MyController extends Controller
    public function main()
        $emailer = resolve(\Programster\PhpMailerWrapper\PhpMailerWrapper::class);


If you find yourself changing your service provider when debugging, remember to keep executing php artisan clear-compiled to be sure the changes are applying.


Last updated: 28th May 2019
First published: 5th October 2018