Laravel with MongoDb Short Guide for Beginners

  • Share this:

Hello, today I want to talk about the Laravel with MongoDb. In programming and how to connect with MongoDb, to write scalable, reusable, and clean code, you need to follow some programming principles.

What is MongoDB?

MongoDB is a NoSQL (Not only SQL) database that stores large volumes of data in the form of JSON-like documents that can change structure over time.

What's is difference between MongoDb and MySql ?

MongoDB is an open-source database developed by MongoDB, Inc.MySQL is a popular open-source relational database management system (RDBMS) that is developed
In MongoDB Stores data in JSON-like documentsIn MySQL, each individual records are stored as ‘rows’ in a table.
In MongoDB documents belonging to a particular class or group as
stored in a ‘collection’.
In MySQL, A ‘table’ is used to store rows (records) of similar type.
MongoDB is NoSQL database.MySQL Structured Query Language (SQL) 
Field Column
Embedded Documents, linkingJoin

MongoDB Server Install

MongoDB has two server editions: Community and Enterprise. Both editions can be installed on almost any operating system or using Docker. To install MongoDB locally, check the official installation documentation. ?


The alternative way is to use the cloud version called MongoDB Atlas, which is not free but comes with a free tier.

Here's a general structure of how MongoDB works with Laravel Eloquent:

general structure

STEP 1: Installing Laravel via Composer

You can ignore this step if you already have an application downloaded, or else run the following command to create a brand new Laravel project.

composer create-project laravel/laravel {directory} 11.0 --prefer-dist

STEP 2: How To Install MongoDB In Laravel ?

Notice: Remember that you need the PHP MongoDB extension to be installed and enabled.

To use MongoDB in your Laravel application, first, you must install the official package, which extends the same model and query builder APIs from Eloquent.

composer require mongodb/laravel-mongodb

Next, we need to register the MongoDB Service Provider in our project.


return [

STEP 3: Configure Database Connection

We must create a database connection in the config/database.php file.

You can connect to your MongoDB deployment by providing a connection URI, also called a connection string. See the connection guide for more details.


'connections' => [
	// add these line code 
	'mongodb' => [ 
            'driver' => 'mongodb',
            // Replace "mongodb://localhost:27017" with the actual connection string
            'dsn' => env('DB_DSN', 'mongodb://localhost:27017'),
            'database' => env('DB_DATABASE', 'laravel'),

After setup MongoDb connection string Finally, we need to set that connection as a default in the environment file.


Now, we can use MongoDB as a database in our application. There are some differences, so let's see how to use MongoDB.

STEP 4: Building Your First Model And Relationships

Today we are going to create a post model. Because of that, we need to have posts in our database. So now we can create a model called ‘Post’ by following the below command.

php artisan make:model Post

Every Model must extend the Model class from the MongoDB.


use Illuminate\Database\Eloquent\Model; 
use MongoDB\Laravel\Eloquent\Model; 
class Post extends Model
    // ...

use Illuminate\Database\Eloquent\Model; 
use MongoDB\Laravel\Eloquent\Model as Eloquent;
class Post extends Eloquent
    // ...

You can change the collection name by overwriting the $collection protected property.


use MongoDB\Laravel\Eloquent\Model as Eloquent;
class Post extends Eloquent
    protected $collection = 'postings'; 
    // ...

Authentication Laravel with MongoDB ?

First, you must change the extended class in the User Model to the one from the MongoDB package to allow users to authenticate your application.


namespace App\Models;

use MongoDB\Laravel\Eloquent\Model as Eloquent;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Auth\Authenticatable as AuthenticatableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Laravel\Sanctum\HasApiTokens;

class User extends Eloquent implements Authenticatable, AuthorizableContract
    protected $collection = 'users';

    use AuthenticatableTrait, Authorizable,HasApiTokens;

Next, by default, Laravel uses the database session driver. If you want to use a database as a session driver, you must create a custom session driver. Alternatively, change the session driver, for example, to file.


There are some Laravel features that MongoDB doesn't support. You can check the full MongoDB's compatibility with Laravel features in the official documentation. In addition to storing data, MongoDB can be used for other features such as queue, cache, locks, and sessions. For more on using MongoDB in Laravel applications, check the official documentation.

About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (53)