Configure MongoDB in Laravel

By | December 18, 2018

Prerequisites:

  • MongoDB(Must be installed and working properly)
  • PHP(Must be installed and working properly)
  • MongoDB PHP driver(Must be installed and working properly)

Let’s start now.

First install the Laravel MongoDB library(https://github.com/jenssegers/laravel-mongodb)

And add the service provider in config/app.php:

You may also register an alias for the MongoDB model by adding the following to the alias array in config/app.php:

Create a database(say learnings) and required collections(say users) in MongoDB(By default no username and password). Now add the details in .env file:

Change your default database connection name in config/database.php:

Now, update the Models(say User.php model) to use MongoDB.

Replace

use Illuminate\Foundation\Auth\User as Authenticatable;

With

use Jenssegers\Mongodb\Auth\User as Authenticatable;

Add following properties in the User model:

To enable soft deletes for a model, apply the [use Jenssegers\Mongodb\Eloquent\SoftDeletes;] to the model:

Keep rest of the things unchanged.

Now your application is ready to use MongoDB. Register and the login as registered user like we do with MySQL.

That’s all.

Leave a Reply

Your email address will not be published. Required fields are marked *