Laravel + MongoDB (via mlab.com) locally

I’m working on a new side project called Howdy (I’ll be sharing more about this project in the coming months).

A couple of the technical requirements that I set for this project were to learn some new technologies along the way.

I’d never built anything with Laravel prior to this project. I had never used Vue.js, or MongoDB either. I wanted to utilize all three of them for this project.

Two weekends ago I set out to get MongoDB working with Laravel locally. I decided to use mLab to host my MongoDB database remotely. I figured it would be pretty straight forward.

Boy was I wrong! 😛

It took me a solid 6 hours to get everything working. As a result, I figured I’d save my future self the trouble of having to ever go through that pain again, and I decided to jot down some notes:

Step 1) Set up Laravel, and your mLab account

I’m not going to walk through either of these – they’re pretty self explanatory.

Step 2) SSH into your local server

I use Homestead with vagrant up & vagrant ssh instead of homestead up & homestead ssh. I feel like there is a difference, but I may be wrong.

Set up your MongoDB Driver

The next few instructions come directly from this article, but I’m just going to repeat them here. You’ll run each of these in your SSH shell:

Step 3) Import the public key used by the package management system

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

Step 4) Create a list file for MongoDB on Ubuntu 16.04

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

Step 5) Reload local package database

sudo apt-get update

Step 6) Install the latest stable version of MongoDB

sudo apt-get install -y mongodb-org

Step 7) Pin a specific version of MongoDB

Run each of these in your command line:

echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-org-shell hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections

Step 8) Start MongoDB

sudo service mongod start

Technically you could just use the mLab Data API to connect, but the native MongoDB driver which you just set up will be much more performant & secure.

Set up Moloquent

Step 9) Import Moloquent

Moloquent is a MongoDB based Eloquent model and Query builder for Laravel. You can import it with composer:

composer require jenssegers/mongodb

You’ll also need to add the following service provider to config/app.php within Laravel:

Jenssegers\Mongodb\MongodbServiceProvider::class,

Update PHP internals

The following code is borrowed from this shell script, but updated for PHP 7.2:

Step 10) Fix pecl errors list

sudo sed -i -e 's/-C -n -q/-C -q/g' `which pecl`;

Step 11) Install OpenSSl Libraries

sudo apt-get install -y autoconf g++ make openssl libssl-dev libcurl4-openssl-dev;
sudo apt-get install -y libcurl4-openssl-dev pkg-config;
sudo apt-get install -y libsasl2-dev;

Step 12) Install PHP7 mongoDb extension

sudo pecl install mongodb;

Step 13) Add extension to your php.ini file

sudo touch /etc/php/7.2/mods-available/mongodb.ini
sudo echo "; configuration for php mongo module\n; priority=30\nextension=mongodb.so" >> /etc/php/7.2/mods-available/mongodb.ini
sudo ln -s /etc/php/7.2/mods-available/mongodb.ini 30-mongodb.ini

Step 14) Add the following to /etc/systemd/system/mongodb.service


[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target

[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

Step 15) Enable Mongo

sudo systemctl start mongodb
sudo systemctl status mongodb
sudo systemctl enable mongodb

Step 16) Restart Nginx & PHP fpm

sudo service nginx restart && sudo service php7.2-fpm restart

Update your Laravel files

Step 17) Add a new database config connection

'mongodb' => array(
            'driver'   => 'mongodb',
            'host'     => env('MONGODB_HOST'),
            'port'     => env('MONGODB_PORT'),
            'username' => env('MONGODB_USERNAME'),
            'password' => env('MONGODB_PASSWORD'),
            'database' => env('MONGODB_DATABASE'),
            'options' => [
                'database' =>  env('MONGODB_DATABASE') // sets the authentication database required by mongo 3
            ]
        ),

Be sure to also update your .env file:

MONGODB_HOST=ds12345.mlab.com
MONGODB_PORT=12345
MONGODB_USERNAME=YOUR-mLAB-USERNAME
MONGODB_PASSWORD=YOUR-mLAB-PASSWORD
MONGODB_DATABASE=YOUR_mLAB-DB

Step 18) Add a new route to web.php

Route::get('/mongo/', 'MongoController@index');

Step 19) Add your controller

namespace App\Http\Controllers;

use App\Mongo;

class MongoController extends Controller
{
    public function index() {
        Mongo::testCall();
    }
}

Step 20) Add your Mongo model

namespace App;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Mongo extends Eloquent
{
    protected $collection = 'users';
    protected $connection = 'mongodb';

    public function scopeTestCall()
	{
    	$user = new Mongo;
	    $user->name = 'Dave';
	    $user->save();
	}
}

And that should do it!

Hope that ends up being helpful to someone else who is in the same boat! 😘

Comments

I don’t do comments on this site, but if you have thoughts, I’d love to hear them. You can email me at its@davemart.in.