Install MongoDB on Laravel Project — Jenssegers/MongoDB

Fiko Borizqy
3 min readOct 7, 2018

--

Today I will show you how to using MongoDB database instead of using mySQL. By default since this story created, we need to manually installing MongoDB driver for laravel, and I will use jenssegers repository and install it by my own way. I’m using laravel version 5.6.* here by the way.

Step 1: Installing the repo to our project

Go to your project directory, in my case it is:

cd /home/fiko/www/project-1

Next, we need to install the jenssegers/mongodb using composer:

composer require jenssegers/mongodb 
composer require jenssegers/mongodb

Step 2: Add the service provider

Edit your config/app.php, and add this to your service providers:

Jenssegers\Mongodb\MongodbServiceProvider::class,
Jenssegers\Mongodb\MongodbServiceProvider::class

Step 3: Setting Up Database configuration

Next, we need to set the database configuration in config/database.php. And putting this code:

'default' => env('DB_CONNECTION', 'mongodb'),
‘default’ => env(‘DB_CONNECTION’, ‘mongodb’),

And these codes as well: (there are 2 options for the database configuration)

'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
]
],
configuration, alternative 1

or this one, configuration, alternative 2:

'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('DB_DSN'),
'database' => env('DB_DATABASE'),
],
configuration, alternative 2

for the second one, you can learn the DSN/URI here: https://docs.mongodb.com/manual/reference/connection-string/

Step 4: Config the .env File

Open up .env file. For alternative 1 on Step 3, use this config:

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=database
DB_USERNAME=username
DB_PASSWORD=password
alternative 1

For alternative 2, use this config:

DB_CONNECTION=mongodb
DB_DSN=mongodb://username:password@127.0.0.1:27017/database_name
DB_DATABASE=database_name
alternative 2

Step 5: Replacing the eloquent

Instead of using Illuminate eloquent by laravel, change and use the eloquent from jenssegers/mongodb:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class ExampleController extends Eloquent {
//
}

— Completed —

Your laravel project using MongoDB by Jens Segers is ready to develope.

--

--

Fiko Borizqy

I wrote these tutorials for myself in future when I forget for the next steps.