Laravel 11 for Beginners: Service Providers

Arlind Musliu Portrait
Arlind Musliu

January 14, 2024 · 3 min read · 37 views

Laravel Blogpost Image

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Laravel Service Providers

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 Illuminate\Support\Facades\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

All service providers are registered in the bootstrap/providers.php configuration file. This file returns an array that contains the class names of your application's service providers:

<?php
 
// This file is automatically generated by Laravel...
 
return [
    App\Providers\AppServiceProvider::class,
    App\Providers\BlogServiceProvider::class, 
];

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
    {
     	$this->app->singleton(Connection::class, function ($app) {
			return new Connection(config('database.default'));
		});
    }

    /**
     * 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:

Laravel
Heading Pattern

Related Posts

Stay up to date

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