10

I am using Lumen 5.3.1. $app->withFacades() and $app->withEloquent() have been uncommented in app.php. In web.php I run the following code:

$app->get('foo', function () {
    return app('db')->select("SELECT * FROM foo");

    return "Connected successfully to database " . DB::connection()->getDatabaseName();
});

The select() call correctly returns data from the foo table. However, DB::connection() returns:

FatalErrorException in Manager.php line 74: 
Call to a member function getConnection() on null

Why does one work but not the other?

ebakunin
  • 3,621
  • 7
  • 30
  • 49
  • Do you have multiple databases configured? Could you try DB::connection(_databasename_)->getDatabaseName() and see? – blackpen Nov 10 '16 at 04:56
  • I only have one configured, using the .env file. When I made the change you suggested I get the same error. – ebakunin Nov 10 '16 at 05:06

2 Answers2

4

I'd say double check your service providers. It looks like you are going through the DB Capsule, when actually that's intended for use out of Laravel/Lumen. Anyway if you are in fact using the Capsule Manager, you probably have to register it in a boot method of the provider, not register.

Also, in order to find out more about what's going on, add this to your test code:

dd(app('db'), DB::getFacadeRoot());

Share the result if you want, this will give more information about the difference between the two methods.

alepeino
  • 9,551
  • 3
  • 28
  • 48
  • The code did not recognize `getFacadeRoot()` from `DB`, so I used `Auth::getFacadeRoot()` instead. The result is a very long data dump. What information are you looking for? – ebakunin Nov 12 '16 at 01:48
  • 1
    `DB` is not a Facade then. Do `dd(DB::class)` then, and check the aliases and registered providers, in order to find out what "DB" is being bound to. Also, are you using any `use` statements? – alepeino Nov 12 '16 at 13:18
  • The `use` statement was the issue. `use Illuminate\Database\Capsule\Manager as DB` gave me access to a `connection()` method but not the correct one. Removing the `use` statement solved the problem. Thank you! – ebakunin Nov 12 '16 at 19:19
0
 app('db')->select("SELECT * FROM foo");
 DB::connection()->getDatabaseName();

try

app('db')->connection()->getDatabaseName();

or

\DB::connection()->getDatabaseName();
Vilintritenmert
  • 125
  • 1
  • 3
  • 9