How to use MongoDb with Laravel Eloquent?

How to use MongoDb with Laravel Eloquent?

In this blog we gonna use MongoDB with Laravel.

How to use MongoDb with Laravel Eloquent?

 

Step 1: Install MongoDB driver for Php

In this blog, we use MongoDB 1.13.0 you can use it as per your preference. Download php_mongodb.dll using the below URL.

 

https://pecl.php.net/package/mongodb/1.13.0/windows 

 

In This Url, you will find many DLL files. Choose your Php version here I download it for Php 7.4. 

 

Note: There will Two options for X64 as well as X86 bit system. one is TS (Thread Safe) and other is NTS (Non Thread Safe) . Download zip file after checking your php version is Thread safe or Non Thread Safe

 

 

Here i have Ts version so i have to download Ts version of extension.

 

You can see that here I have the TS version of PHP so I have to download the TS version of the MongoDB extension zip file.

After Download exract zip file and there you will find php_mongodb.dll file. Copy that file and paste it into your php/ext folder

 

Here i copy php_mongodb.dll from downloaded Zip file

 

Here, We copy php_mongodb.dll into ext folder of the PHP folder.

Now, you have to enable the MongoDB extension from the Laragon server or php.ini 

First, we enable it from php.ini file,

 

Open your php.ini file and Find this line ;extension=mongodbnow remove ; from it. ( It will enable mongodb extension ) 

Now, save file and start Laragon server or Xampp server, Now your mongodb is ready to connect with php.

 

Step 2: Install the below package via Composer.

 composer require jenssegers/mongodb

In case your Laravel version does NOT autoload the packages, add the service provider to config/app.php:

Jenssegers\Mongodb\MongodbServiceProvider::class,

 

Step 3: Configure database.php for MongoDB.

Now, you have to add a MongoDB connection into config/database.php.

'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', 'homestead'),
    'username' => env('DB_USERNAME', 'homestead'),
    'password' => env('DB_PASSWORD', 'secret'),
    'options' => [
        // here you can pass more settings to the Mongo Driver Manager
        // see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters that you can use

        'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+
    ],
],

 

Step 4: Set Database name and password into .env file

Add your MongoDB username, database name, and password to the .env file. Here DB_CONNECTION and DB_PORT is as essential as a username and password.

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=your_db
DB_USERNAME=your_username
DB_PASSWORD=your_password

 

Step 5: Setup Model according to MongoDB package

This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.

use Jenssegers\Mongodb\Eloquent\Model;

class ModelName extends Model
{
    //
}

Now, you have to give your collection name into the model, but just like a standard model, the MongoDB model class will know which collection to use based on the model name. For User, the collection users will be used.

To change the collection, pass the $collection property:

use Jenssegers\Mongodb\Eloquent\Model;

class ModelName extends Model
{
    protected $collection = 'my_collection';   // If your collection name is 'model_names' then you don't have to add this varibable.
}

Note: MongoDB documents are automatically stored with a unique ID that is stored in the _id property. If you wish to use your own ID, substitute the $primaryKey property and set it to your own primary key attribute name.

use Jenssegers\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $primaryKey = 'id';  // Mongo will also create _id, but the 'id' property will be used for primary key actions like find().
}

 

Step 6: Store and retrieve data from MongoDB.

Here, we have a simple example for storing and retrieving data from MongoDB.

use Jenssegers\Mongodb\Eloquent\Model;

class Toy extends Model
{
    protected $collection = 'my_toys';
     
    public function store($request)
    {
            $res = new self;
            $res->title = $request->title;
            $res->description = $request->description;
            $res->save();

           return true; 
    }
   
    public function getToys($request)
    {
           // For All data without any condition
           $all_data = self::all(); 
           
           // With where() condition multiple data
           $conditional_data = self::where('name','car')->get();   // You can use every statement like take(), orWhere(), whereIn(), orderBy() and allothers that used in normal model

           // Only single data 
           $first_data = self::where('name','car')->first();
           $findmethod = self::find($request->id);

          return true; 
    }

}

 

Step 7: Make Model Authenticable

You can make the model authenticable with two lines of code.This package includes a MongoDB Authenticatable Eloquent class Jenssegers\Mongodb\Auth\User that you can use to replace the default Authenticatable class Illuminate\Foundation\Auth\User for your User model.

use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{
     // Start Code Here
}

 

Step 8: Eloquent Relationship with MongoDB collections

Here is example of every relationship.

use Jenssegers\Mongodb\Eloquent\Model;

class User extends Model
{
    // BelongsToMany Relationship
    public function groups()
    {
        return $this->belongsToMany(Group::class,'secondary_id','prmary_id');
    }
    
    // hasMany Relationship
    public function items()
    {
        return $this->hasMany(Group::class,'secondary_id','prmary_id');    // Similar  use hasOne method for one-to-one relationship
    }
    
    // BelongsTo Relationship
    public function group()
    {
        return $this->belongsTo(Group::class,'secondary_id','prmary_id');
    }
}

 

Step 9: Now, Run your project and using MongoDB with Laravel Eloquent.