MongoDB Database Connection In Laravel

  • 15-11-2022
  • 1619
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

MongoDB Database Connection In Laravel; In this post, you will learn about MongoDB database connection with the laravel application. When you are developing a big user data collection application and you want to work with lightweight data without any loading. that time MongoDB is the best option for the server side. MongoDB is not a relational database.

MongoDB is a source available cross-database platform document-oriented database program. This is classified as a NoSQL database program. In the laravel application MongoDB database connection we must need to follow the basic process, therefore required little configuration in the application for the MongoDB connection.

MongoDB connection with the laravel application you first need to check whether the MongoDB extension is available in the apache server or not. Because it must be required. So follow the below step and connection MongoDB to your laravel application.

Step 1. Install MongoDB Extension

DLL File Download Links Download click on the download link and download the MongoDB extension file from there, by default xampp not providing MongoDB extension, we just need to install it manually.

After downloading a file from the link go to the php.ini file in your apache server and paste this extension into this file. If The extension is already available in the file just uncomment it.

extension=php_mongodb.dll

After Adding php_mongodb.dll in the php.ini file restart your apache server.

Step 2. Install Composer

Install Composer using the below-provided command in your command prompt, This command will install the core dependency of your application for the MongoDB connection and retrieve and insert data to the MongoDB database.

Choose Laravel 9 install 3.9.x version, Laravel 8 install 3.8.x version, Laravel 6 install 3.6.x version

composer require jenssegers/mongodb
For Laravel 8
composer require jenssegers/mongodb 3.8.x

Step 3. Add Service Provider

In case sometime laravel does not autoload the installed package in the application. Goto config/app.php file and check whether the service provider imported or not in the application. If it's not loaded in the service provider then please important in your provider's array attribute.

'providers' => [
     ...
     ...
     Jenssegers\Mongodb\MongodbServiceProvider::class,
];

Step 3. Migration Setup

Import use Illuminate\Foundation\Testing\DatabaseMigrations; in each laravel migration file, and also defined in the class as use.

use Illuminate\Foundation\Testing\DatabaseMigrations;

use DatabaseMigrations;

Exmaple Users table migration add like following

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Foundation\Testing\DatabaseMigrations; //ADD

class CreateUsersTable extends Migration
{
     use DatabaseMigrations;

     /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
     {
          Schema::create('users', function (Blueprint $table) {
               $table->id();
               $table->string('name');
               $table->enum('status',['active','inactive'])->default('active');
               $table->string('email')->unique();
               $table->timestamp('email_verified_at')->nullable();
               $table->string('password');
               $table->longtext('post')->nullable();
               $table->rememberToken();
               $table->timestamps();
          });
     }

     /**
     * Reverse the migrations.
     *
     * @return void
     */
     public function down()
     {
          Schema::dropIfExists('users');
     }
}

Step 4. Database Config

By default laravel not providing MongoDB database credential keys and core connection settings. Therefore we need to go database.php file and inside the connections attribute add the below-provided configurations.

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' => [
          'appname' => 'homestead',
     ],
],

Step 5. .env Config

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=laravel
DB_USERNAME=
DB_PASSWORD=

Step 6. Model Config

Import use Jenssegers\Mongodb\Eloquent\Model; model class from the service provider. This action you need to do in every model which you created in the application. In this case Book model extends the Model which we imported at the top as used.

use Jenssegers\Mongodb\Eloquent\Model;

class Book extends Model
{
     protected $primaryKey = 'id';
}

Define connection in the model using the $connection property in the model class, This properly overrides the name database connected that should be used when utilizing the registered model.

use Jenssegers\Mongodb\Eloquent\Model;

class Book extends Model
{
     protected $connection = 'mongodb';
}
Extending the authentication base model
use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{

}
Soft Deletes Base on Model
use Jenssegers\Mongodb\Eloquent\SoftDeletes;

class User extends Model
{
     use SoftDeletes;

     protected $dates = ['deleted_at'];
}

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :