Table of contents
In this post, I will share how to create a custom service provider in Laravel 9. If you have a feature that needs to change the Laravel locale or maybe change the timezone base on your application settings. Then we are using a service provider to do this.
Â
Create Service Provider in Laravel using Artisan
Let's run the command php artisan make:provider AppConfigServiceProvider
. AppConfigServiceProvider is your service provider class name. You can change with your class name need.
Â
Once done it will generate a file AppConfigServiceProvider.php
inside app/Providers
. Here is the code generated below:
Â
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppConfigServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
}
}
Â
As you can see there are two methods register()
and boot()
.
Â
The register() method
The register()
method in the Service Provider allows us to define bindings to our service container. Here is the sample code below:
Â
public function register()
{
$this->app->singleton(any_class, function ($app) {
return new AnyClass($app);
});
}
Â
The $this->app
is a global variable that is available inside Laravel which use to access the internal settings of the application.
Â
The singleton
is a trait that is taken from the Ruby module. It will help to bind a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls instead of a new instance.
Â
The boot() method
The boot()
method is used to access all the services which are registered in register()
method. That's why in my example if we want to change the Laravel locale and timezone from its original configuration we need to implement the code inside the boot()
method so that we can access all the registered services.
Â
Here is my example to do it.
Â
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
app()->setLocale(
setting('locale')
??
config('app.locale')
);
config([
'app.timezone' =>
setting('timezone')
??
config('app.timezone')
]);
}
Â
Once done configuring your Custom Provider we need to register it inside config/app.php
to enable it.
Â
How to do it? First search the providers key or this 'providers' => [...]
then inside that array add the namespace or this App\Providers\AppConfigServiceProvider::class,
. See the example below:
Â
'providers' => [
...
/**
* Setting Service Providers..
*/
App\Providers\AppConfigServiceProvider::class,
],
Â
As you can see we change the locale and timezone based on our application settings. I hope it helps :)
Â
NOTE: If you want to use the setting()
function you need to install akaunting/laravel-setting
package.
Read next