How to Create a Custom Service Provider in Laravel

In this short tutorial, we are going to create and register a custom service provider in Laravel.

Quick Tip : How to Determine if a View Exists in Laravel

First, open your command prompt, navigate to your project folder and run the following command.

php artisan make:provider DemoServiceProvider

This will generate a new file with name DemoServiceProvider.php located at app\Providers. Your service provider should look something like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class DemoServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

As you can see, all the service providers extends Laravel’s ServiceProvider class.

To register this provider navigate to config directory located in the root directory of your application and open app.php file. Now, we need to add our provider to the array of providers,

'providers' => [
    .
    .
    .
    App\Providers\DemoServiceProvider::class,
],

And that’s it. We have successfully created and registered a Laravel service provider.

0 Comments

Leave a Comment.