Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Service Providers in Laravel 11: Main Things You Need To Know

Service Providers have been the core functionality of Laravel since the beginning. However, in Laravel 11, the list of providers changed, with only AppServiceProvider left. So, what do developers need to know now?


Quick Theory: Main Purpose of Service Providers

The primary purpose of the service providers is to be the central place for registering classes or various global settings.

In my opinion, it should have been called "Class Configuration" or something similar, not a Service Provider, to avoid confusion. But we need to work with what we have, right?

In the AppServiceProvider, you would typically register singletons, event listeners, and optional extra configurations for various Laravel features like API resources, polymorphic relations, etc.


Default "Empty" AppServiceProvider

After you install Laravel 11, the AppServiceProvider looks like this:

app/Providers/AppServiceProvider.php:

namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
 
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
 
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

What's the difference between the register() and boot() methods?

The short explanation is that the register() method for all providers is called earlier than the boot() method.

  • register(): here, you can add simple binding and singletons.
  • boot(): this is where you can perform tasks that may depend on other registered providers. Here, you can add macros, event listeners, define gates, etc.

Now, let's look at the usage examples for both methods.


Example Use-Cases: register() Method

You can register a singleton in the service provider, ensuring only one instance exists throughout your application.

Example 1. Filament: Register Custom Login Page

We overwrite the response using Singleton here with a custom response class.

public function register(): void
{
$this->app->singleton(
\Filament\Http\Responses\Auth\Contracts\LoginResponse::class,
\App\Http\Responses\LoginResponse::class
);
}

Notice: You don't know much about Singleton? We cover it in the course Design Patterns in Laravel

Example 2. Telescope: Register it Only Locally

Here's another...

The full tutorial [6 mins, 1190 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses