How to use mongoDB with your Lumen API
Tags: mongodb, laravel, tutorial, beginners
Published: 2019-08-12 16:48:30

I’m currently building a RESTful API using [Lumen](https://lumen.laravel.com/), from the guys that brought to us [Laravel](https://laravel.com/). Lumen is a great micro-framework with most of the spectacular features from Laravel like Eloquent, caching, validation, routing, middleware and so on and so forth. The API I’m building it’s supposed to serve an, yet to develop, iOS app that it’s meant to support the information system of the college where I attend, which don’t correctly support mobile devices.

This would be a pretty straightforward project but **unfortunately,** they won’t make my life easy and won’t let me access the existing database. It sucks, right? However, they have a [SOAP Web Service](https://en.wikipedia.org/wiki/SOAP) available that I can use. But… If I used their web service alongside my API every time I made a request it would take ages to get the information I’ve requested. This is, obviously, a shitty way to do things. So I’ve decided to implement a database where I can store the data by myself.

I’m fully aware that we shouldn’t repeat data but I can’t find a better way this time. I’ve decided to develop some Python bots that would periodically fetch information using the SOAP web service and store it in the database to be later served using the REST API. I’ve decided to use [mongoDB](https://www.mongodb.com/) mostly for its flexibility, performance, and scalability. I’m using mongo 3.4 so all the commands below are tested for this version.

> So… How to setup Lumen to use mongoDB

[Jens Segers](https://jenssegers.com/) has a wonderful Composer package to use mongoDB with Laravel: [Laravel MongoDB](https://github.com/jenssegers/laravel-mongodb). Looking at the repo instructions you can see that, for using with Lumen and after you installed the package, edit the file `bootstrap/app.php` and make it look like:

```php
$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);

$app->withEloquent();
```

After this, you should create the `config/database.php` file and it’s contents are:

```php
<?php
    return [
        'default' => 'mongodb',
        'connections' => [
            'mongodb' => [
                'driver' => 'mongodb',
                'host' => env('DB_HOST', 'localhost'),
                'port' => env('DB_PORT', 27017),
                'database' => env('DB_DATABASE'),
                'username' => env('DB_USERNAME'),
                'password' => env('DB_PASSWORD'),
                'options' => [
                    'database' => 'admin' // sets the authentication database required by mongo 3
                ]
            ],
        ],
        'migrations' => 'migrations',
    ];
```

This will override `vendor/laravel/lumen/config/database.php` and it will allow you to use mongo with your Lumen project. After this you have you change our `.env` file and append:

```php
DB_CONNECTION=mongodb
DB_HOST=<dbHost>
DB_PORT=27017
DB_DATABASE=<dbName>
DB_USERNAME=<dbUser>
DB_PASSWORD=<dbUserPassword>
```

Out of the box mongo doesn’t have any authentication details. You can add your own user to it using:

```
use admin
db.createUser( { user: "<dbUser>",
          pwd: "<dbUserPassword>",
          roles: [ "userAdminAnyDatabase",
                   "dbAdminAnyDatabase",
                   "readWriteAnyDatabase"

] } )
```


Now I’m able to use Lumen’s `artisan` commands, for instance, I can create my `users` table using:

```bash
php artisan make:migration create_users_table --create=users
```

I’ve modified the migration file like:

```php
public function up() {
    Schema::create('users', function (Blueprint $table) {
        $table->increments('_id');
        $table->string('username');
        $table->string('password');
        $table->timestamps();
    });
}
```

Now I can use `php artisan migrate` and I’ll see my newly created collection.