Laravel

Laravel Service Providers Notes

Article Thumbnail

Description

This article was originally published on my old blog on Tuesday, May 16, 2023.


What is a service provider

Serivce providers are just classes to register some global functionalities.

This image illustrates the Laravel request lifecycle, that shows that Service providers are registered and booted at the beginning of every Laravel application. As mentioned in the article linked here, all service providers listed in config/app.php are executed twice, following a top-to-bottom iteration.

The first iteration is looking for an optional method register() which may be used to initiate something before the boot() method.

Then, the second iteration executes the boot() method of all providers. Again, one by one, from top to bottom of the 'providers' array.

And then, after all the service providers have been processed, Laravel goes to parsing the route, executing the Controller, using Models, etc.

In the filament documentation, they mention the following:

You may customize navigation groups by calling Filament::registerNavigationGroups() from the boot() method of any service provider

This means that it is not necessary to use a specific service provider class; however, for better organization, we use service classes. Povilas Korop explains this in his video link

Creating a Custom Service Provider

To create a custom service provider, you can follow these steps:

  1. Generate the ViewServiceProvider using the following command:
php artisan make:provider ViewServiceProvider
  1. In the ViewServiceProvider class, define the boot method as shown below to make a blade directive global:
public function boot(): void
{
  Blade::directive('greeting', function ($expression) {
  return "<?php echo 'Hello ' . ($expression); ?>";
  });
}
  1. Include the service provider in the config/app.php file, under the providers array:
'providers' => ServiceProvider::defaultProviders()->merge([
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
ViewServiceProvider::class,
])->toArray(),

Links

Here are some helpful resources I found on Google for understanding Laravel Service Providers

  • Laravel Request lifecycle (Arabic) link
  • Service Providers in Laravel: What They Are and How to Use Them link
  • Laravel Service Providers: All You Need to Know link