DEV Community

Morcos Gad
Morcos Gad

Posted on

Service Providers - Laravel

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

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());
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

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

// app/Providers/AppServiceProvider.php
use Illuminate\Database\Eloquent\Model;

public function boot()
{
    Model::preventLazyLoading(! $this->app->isProduction());
}
Enter fullscreen mode Exit fullscreen mode

Which providers are loaded? It's defined in the config/app.php array

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,

    ],

];
Enter fullscreen mode Exit fullscreen mode
  • Create Your Custom Service Provider

You can generate it with this command

php artisan make:provider ViewServiceProvider
Enter fullscreen mode Exit fullscreen mode

inside of boot() add Blade directive code

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'); ?>";
        });
    }
} 
Enter fullscreen mode Exit fullscreen mode

To be executed, this new provider should be added to the array of providers in config/app.php, as mentioned above

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,
    ],
];
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)