Laravel Service Providers

Lesson 44 of 50

88%
1. What Is a Service Provider?

A Service Provider is a central place in Laravel where application services can be registered and configured. Laravel uses service providers to initialize many of its core features and application services.

Common tasks performed by service providers include:

  • Registering service container bindings.
  • Registering application services.
  • Configuring application components.
  • Registering event listeners and other boot-time behavior.

Laravel applications typically contain an AppServiceProvider, which is a convenient place for application-specific service registration.

2. Understand the AppServiceProvider

In a standard Laravel application, the AppServiceProvider is located at:

app/Providers/AppServiceProvider.php

Its basic structure looks like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Register application services here.
    }

    public function boot(): void
    {
        // Configure services after providers are registered.
    }
}

Two important methods:

  • register() — registers bindings and services in the container.
  • boot() — runs after service providers have been registered, allowing services to be configured.
3. The register() Method

Use the register() method to bind an interface to its implementation or register other application services.

First, create an interface:

app/Contracts/MessageService.php
<?php

namespace App\Contracts;

interface MessageService
{
    public function send(): string;
}

Create its implementation:

app/Services/WelcomeMessageService.php
<?php

namespace App\Services;

use App\Contracts\MessageService;

class WelcomeMessageService implements MessageService
{
    public function send(): string
    {
        return 'Welcome to Laravel!';
    }
}

Now register the binding in AppServiceProvider:

use App\Contracts\MessageService;
use App\Services\WelcomeMessageService;

public function register(): void
{
    $this->app->bind(
        MessageService::class,
        WelcomeMessageService::class
    );
}

Keep the existing provider class and add these imports at the top of the file. Place the binding inside its existing register() method.

Laravel can now resolve MessageService using WelcomeMessageService.

4. The boot() Method

The boot() method is used to configure application services after providers have been registered.

Example using a view composer:

use Illuminate\Support\Facades\View;

public function boot(): void
{
    View::composer('dashboard', function ($view) {
        $view->with('siteName', 'Soopro Pathshala');
    });
}

This example shares the siteName variable with the view named dashboard whenever that view is rendered.

For example, inside resources/views/dashboard.blade.php:

<h1>Welcome to {{ $siteName }}</h1>

Add the import at the top of AppServiceProvider.php and put the code inside the existing boot() method.

5. Create a Custom Service Provider

You can create a separate service provider to organize related service registrations.

Run this Artisan command:

php artisan make:provider PaymentServiceProvider

Laravel creates a provider class, typically at:

app/Providers/PaymentServiceProvider.php

Example provider:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\PaymentService;

class PaymentServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(
            PaymentService::class,
            function ($app) {
                return new PaymentService();
            }
        );
    }

    public function boot(): void
    {
        // Additional payment configuration can go here.
    }
}

This example assumes that you have created the App\Services\PaymentService class.

In Laravel versions that support the make:provider command, the framework may register the new provider automatically. If it is not registered, add it to the provider list for your Laravel version.

6. Understand bind() and singleton()

Laravel provides different ways to register objects in the service container.

Using bind():

$this->app->bind(
    MessageService::class,
    WelcomeMessageService::class
);

A new instance is generally resolved each time the binding is requested.

Using singleton():

$this->app->singleton(
    MessageService::class,
    WelcomeMessageService::class
);

The container reuses the same resolved instance for that singleton binding during the application's container lifecycle.

Quick comparison:

Method Behavior
bind() Resolves a new instance on each resolution.
singleton() Reuses the resolved instance.

Choose the registration method according to whether the service should be recreated or shared.

7. Use a Registered Service in a Controller

After registering an interface binding, inject that interface into a controller.

<?php

namespace App\Http\Controllers;

use App\Contracts\MessageService;

class WelcomeController extends Controller
{
    public function index(MessageService $messageService)
    {
        return response()->json([
            'message' => $messageService->send(),
        ]);
    }
}

Register the route in routes/web.php:

use App\Http\Controllers\WelcomeController;
use Illuminate\Support\Facades\Route;

Route::get('/welcome', [WelcomeController::class, 'index']);

Start the development server:

php artisan serve

Visit:

http://127.0.0.1:8000/welcome

Expected JSON response:

{
    "message": "Welcome to Laravel!"
}

Laravel resolves the interface through the binding in your service provider and injects the implementation into the controller.

8. Service Provider Best Practices
  • Register container bindings inside register().
  • Use boot() for configuration that should run after providers are registered.
  • Keep service providers focused on registration and configuration.
  • Use interfaces when multiple implementations may be needed.
  • Use singleton() only when sharing an instance is appropriate.
  • Avoid performing slow operations such as external API calls directly during provider booting.
  • Do not put controller request-handling logic inside a service provider.
  • Check your Laravel version's provider registration mechanism.

Remember:

A service provider registers or configures services. The service container resolves dependencies when application code requests them.

9. Practice Assignment

Build a welcome-message service for your application.

  1. Create a MessageService interface.
  2. Create a WelcomeMessageService class.
  3. Register the interface binding in AppServiceProvider.
  4. Create a WelcomeController.
  5. Inject MessageService into the controller.
  6. Create a /welcome route.
  7. Test the route and check the JSON response.

Bonus Task:

Create a second implementation named HindiWelcomeMessageService. Change the service provider binding and observe how the controller can remain unchanged.

Quick Quiz

1. What is the main purpose of a Laravel service provider?




2. Which method is commonly used to register container bindings?




3. What does singleton() do?