Search

Laravel with MongoDb Short Guide for Beginners

  • Share this:
post-title

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 ?

MongoDBMySQL 
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) 
CollectionTable
DocumentRow
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.

//bootstrap/app.php:

return [
    App\Providers\AppServiceProvider::class,
    MongoDB\Laravel\MongoDBServiceProvider::class, 
];

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.

//config/database.php:

'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.

DB_CONNECTION=mongodb 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=project
DB_USERNAME=root
DB_PASSWORD=

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.

<?php

use Illuminate\Database\Eloquent\Model; 
use MongoDB\Laravel\Eloquent\Model; 
 
class Post extends Model
{
    // ...
}
 
<?php

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.

<?php

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.

//app/Models/User.php:
<?php

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.

SESSION_DRIVER=file 
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

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)