Service Providers - Laravel
Tags: laravel, php, webdev, programming
Published: 2022-04-24 17:30:22

It is great that I find this article https://laravel-news.com/service-providers that talks about Service Providers in Laravel and explains the importance of this feature and how to use it in our projects. It is better to delve into it, but I will talk about the main points in the article.

Let's start with the default service providers included in Laravel, they are all in the app/Providers folder
- AppServiceProvider
- AuthServiceProvider
- BroadcastServiceProvider
- EventServiceProvider
- RouteServiceProvider

Inside `` boot() `` of that method, you can write any code related to one of those sections: auth, events, routes, etc. In other words, Service Providers are just classes to register some global functionality
```php
class RouteServiceProvider extends ServiceProvider
{
    public const HOME = '/dashboard';
 
    public function boot()
    {
        $this->configureRateLimiting();
 
        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->group(base_path('routes/api.php'));
 
            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }
 
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}
```
One popular example of adding code to the AppServiceProvider is about disabling the lazy loading in Eloquent. To do that, you just need to add two lines into the boot() method
```php
// app/Providers/AppServiceProvider.php
use Illuminate\Database\Eloquent\Model;
 
public function boot()
{
    Model::preventLazyLoading(! $this->app->isProduction());
}
```
Which providers are loaded? It's defined in the config/app.php array
```php
return [
 
	// ... other configuration values
 
    'providers' => [
 
        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
 
        // ... other framework providers from /vendor
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,
 
        /*
         * PUBLIC Service Providers - the ones we mentioned above
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
 
    ],
 
];
```
- Create Your Custom Service Provider

You can generate it with this command
```php
php artisan make:provider ViewServiceProvider
```
inside of boot() add Blade directive code
```php
namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
 
class ViewServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
 
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }
} 
```
To be executed, this new provider should be added to the array of providers in config/app.php, as mentioned above
```php
return [
    // ... other configuration values
 
    'providers' => [
 
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
 
        // Add your provider here
        App\Providers\ViewServiceProvider::class,
    ],
];
```

He talked about the main points and I hope you will visit the source to dig deeper and learn some examples from Open-Source Projects and I hope you enjoyed.