Making a service provider but want to inject the Database service into it

So Ive learned how to make simple service providers that call a helper method from a helper folder.

What I'm wondering is how to make a service provider that has the dependency of an already defined illuminate service. Specifically, the database service.

The following does not appear to be working, and I was under the impression that the boot method is called after all of the other services have been instantiated.

I'm a little confused at the moment.


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\DatabaseServiceProvider;
use App\Helpers\FetchGlobal;

class FetchGlobalServiceProvider extends ServiceProvider

    public function boot(DatabaseServiceProvider $db)
        // do stuff with $db
        return "test";

    public function register()
nkiermaier replied 1 week ago

According to the docs this seems like it should work? . (see Boot Method Dependency Injection)

ahmedash95 replied 1 week ago

You don't need a service provider instance .. you need the class that was created by service provider .. your code should look like

public function boot(\Illuminate\Support\Facades\DB $db)
    // do stuff with $db
    return "test";

because the database service provider register a db singleton

$this->app->singleton('db', function ($app) {
            return new DatabaseManager($app, $app['db.factory']);

also you could use

$db = $app->make('db')

instead of injecting

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us