Laravel for Beginners: Service Providers

Arlind Musliu Portrait

Arlind Musliu

January 14, 2024 · 3 min read · 20 views

Laravel Blogpost Image

In Laravel, service providers are the central place for configuring the core behavior of your application. They are the backbone of your app's functionality, bootstrapping all the necessary services and components.

What are Service Providers?

Service providers in Laravel are special classes where you can register and boot services, such as database connections, mail services, and custom logic. They tell Laravel how to glue different parts of your application together. Each provider can both register and configure services, making them ready for use across your app.

Understanding the Service Provider

A service provider extends the ServiceProvider class and contains two primary methods: register and boot.

The Register Method

The register method is used to bind services into the Laravel service container. This is where you can define how services are created, using simple or complex logic.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Connection;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(Connection::class, function ($app) {
			return new Connection(config('database.default'));
		});
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

The Boot Method

The boot method is where you can interact with services that have been registered by the framework or other service providers. It's a place to add additional functionality, like event listeners or middleware, or even to modify services that have already been registered.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(Connection::class, function ($app) {
			return new Connection(config('database.default'));
		});
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        View::share('latestPosts', Post::latest()->take(5)->get());
    }
}

Creating Your Own Service Provider

For your blog, you might want to create a service provider to encapsulate specific functionality, such as a custom logging service or a content management feature.

To create a new service provider, use the command:

php artisan make:provider BlogServiceProvider

This command will create a new BlogServiceProvider in the app/Providers directory.

Registering a Service Provider

Once you've created your service provider, you need to register it with Laravel. You can do this by adding it to the providers array in the config/app.php configuration file.

<?php

use Illuminate\Support\Facades\Facade;
use Illuminate\Support\ServiceProvider;

return [

    // other config options

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => ServiceProvider::defaultProviders()->merge([
        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\Filament\AdminPanelProvider::class,
        App\Providers\RouteServiceProvider::class,
		App\Providers\BlogServiceProvider::class,
    ])->toArray(),

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => Facade::defaultAliases()->merge([
        // 'Example' => App\Facades\Example::class,
    ])->toArray(),

];

Using Service Providers

Let's say you want to create a set of custom helper functions for your blog, or you want to define a global variable that's accessible in all views. You can do this within a service provider.

For instance, you might want to share the top five latest posts with all views so that you can display them in a sidebar on every page:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class BlogServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
       //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        view()->composer('*', function ($view) {
			$view->with('latestPosts', Post::latest()->take(5)->get());
		});
    }
}

By placing this code in the boot method of your service provider, you're instructing Laravel to make the $latestPosts variable available to all views, which can then be easily displayed in your blog's sidebar.

Conclusion

Service providers are a fundamental part of the Laravel framework, giving you control over how services are registered and booted in your application. They are incredibly powerful for managing dependencies and organizing the way your app works under the hood.

Upcoming Articles in the Series

  1. Laravel for Beginners: Form Requests and Validation Rules

  2. Laravel for Beginners: Task Scheduling for Automation

  3. Laravel for Beginners: Error Handling


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!