Camron Cade

Artisan web development, mostly using Laravel.

DB instance without using facades in Laravel's Lumen

The point of Lumen is that it is light and fast, and so by default helpful tools like Eloquent and Facades are disabled. I like to try and keep it light when I am using Lumen, so I opt to not turn them on.

If you, like me, are used to using the facade DB for building queries in Laravel, you won't be able to do that with Lumen out of the box. Instead, you either need to enable facades in the bootstrap/app.php file, or you need a way to access the database class without the facade.

The solution without enabling facades: Use the IOC container.

You can access the DB instance with app('db').

So DB::table('posts')->first() becomes app('db')->table('posts')->first().

Of course, if you are going to use it more than once on any given request, it's best to save it as a variable and access it using the variable.

In my Controllers, I put it in a constructor:

public function __construct()  
    $this->db = app('db');

Now, anytime I would normally call the DB facade, I can just replace it with $this->db.

Seems simple enough to me!

As always, I welcome feedback and would love to hear about a better way to do this.