---
title: How to use MongoDB in Laravel – Jaeves Codelab
description: In MySQL Database we stores the records in the form of rows and tables. But we need to define the structure of table and columns before inserting records.
---

[Skip to content](https://jaeves.com/codelab/how-to-use-mongodb-in-laravel#main-content)

 Close

SEARCH

[Discover Jaeves for Free](https://app.jaeves.com/login)

[![jaeves-2025-logo](https://jaeves.com/hubfs/logos/jaeves-2025-logo.svg)![jaeves-2025-logo](https://jaeves.com/hubfs/logos/jaeves-2025-logo.svg)](https://jaeves.com/)

[Discover Jaeves for Free](https://app.jaeves.com/login)

Quick results for "{search\_term}"

TABLE OF CONTENTS

loading...

Oct 2, 2023, 6:32:54 PM2 min read

# How to use MongoDB in Laravel

[Previous](https://jaeves.com/codelab/card-components-in-react)

<https://jaeves.com/codelab>

[Next](https://jaeves.com/codelab/create-swagger-configuration-in-laravel)

In MySQL Database we stores the records in the form of rows and tables. But we need to define the structure of table and columns before inserting records. MySQL is quite slow in comparison to MongoDB while dealing with large databases. In this tutorial we will learn how to use mongodb in laravel.

MongoDB represents data as JSON documents. In MongoDB we can do Real-time analytics, content management, internet of things, mobile apps. No schema definition required so lesser risk of attack due to design. It has the ability to handle large unstructured data. MongoDB uses JavaScript as query language. In MongoDB no restrictions on schema design. MongoDB has a pre-defined structure that can be defined and adhered to, but also, if you need different documents in a collection, it can have different structures.

## Using MongoDB with Laravel

To use MongoDB in Laravel we will use [Laravel MongoDB package](https://github.com/jenssegers/laravel-mongodb#eloquent). This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library extends the original Laravel classes, so it uses exactly the same methods.

### Installation

We should have the MongoDB PHP driver installed. You can find installation instructions at [http://php.net/manual/en/mongodb.installation.php](http://php.net/manual/en/mongodb.installation.php). We can use in Laravel 6 and above.

### Install the jenssegers/mongodb package via Composer

```
composer require jenssegers/mongodb
```

Now, add the service provider to config/app.php

```
Jenssegers\Mongodb\MongodbServiceProvider::class,
```

## Laravel MongoDB Configuration

Add a new mongodb connection to config/database.php

```
'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'dsn' => env('DB_DSN'),
    '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+
    ],
],
```

## Create a Eloquent Model with MongoDB

```
use Jenssegers\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $collection = 'my_books_collection';
}
```

**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';
}
```

## Using MongoDB in Laravel Authentication

You need to replace the default Authenticatable class Illuminate\\Foundation\\Auth\\User with MongoDB Authenticatable Eloquent class Jenssegers\\Mongodb\\Auth\\User.

```
use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{

}
```

## MongoDB Query In Laravel

```
// Mongo will also create _id, but the 'id' property will be used for primary key actions like find().
Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']);
```

### Retrieving all models

```
$users = User::all();
```

### Retrieving a record by primary key

```
$user = User::find('517c43667db388101e00000f');
```

### Offset & Limit (skip & take)

```
$users = User::skip(10)
        ->take(5)
        ->get();
```

The [Original Author Package details is here.](https://github.com/jenssegers/laravel-mongodb#eloquent) Also you can read about query and usage in details here.

##### Recommendation

[Using MongoDB in Node.js](https://jaeves.com/codelab/how-to-use-mongodb-in-node-js/)

[How to validate form in ReactJS](https://jaeves.com/codelab/how-to-validate-form-in-reactjs/)

[How to create charts in ReactJS](https://jaeves.com/codelab/how-to-create-charts-in-reactjs/)

[Basic Query In MongoDB](https://jaeves.com/codelab/how-to-query-in-mongodb/)

 

For more [Mongodb Tutorials Click here](https://jaeves.com/codelab/tag/mongodb/), [Node.js Tutorials Click here](https://jaeves.com/codelab/tag/nodejs/).

COMMENTS

## RELATED ARTICLES

[![logo](https://jaeves.com/hs-fs/hubfs/jaeves-logo-230917.png?width=140&height=45&name=jaeves-logo-230917.png "logo")](https://jaeves.com/)

Jaeves is a trailblazing AI-powered content generation tool that revolutionizes your content creation journey. Its user-friendly interface, extensive customization options, and innovative approach make it an invaluable asset for all your content needs. Transform your content strategy with Jaeves today.

All rights reserved

- [Privacy Policy](https://jaeves.com/privacy-policy)

```json
{
  "@context" : "https://schema.org",
  "@type" : "Organization",
  "address" : {
    "@type" : "PostalAddress",
    "addressCountry" : "Germany",
    "addressLocality" : "Speyer",
    "addressRegion" : "Rheinland-Pfalz",
    "postalCode" : "67346",
    "streetAddress" : "Gerhart-hauptmann-Str"
  },
  "knowsLanguage" : "en",
  "logo" : {
    "@type" : "ImageObject",
    "url" : "https://139767802.fs1.hubspotusercontent-eu1.net/hubfs/139767802/logo-2024-less-points.svg"
  },
  "name" : "Jaeves AI",
  "url" : "https://jaeves.com/codelab/how-to-use-mongodb-in-laravel"
}
```

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "abstract" : "In MySQL Database we stores the records in the form of rows and tables. But we need to define the structure of table and columns before inserting records.",
  "author" : {
    "@type" : "Person",
    "name" : "Admin"
  },
  "dateModified" : "",
  "datePublished" : "",
  "headline" : "How to use MongoDB in Laravel",
  "image" : "",
  "inLanguage" : "en",
  "keywords" : "[Laravel, MongoDB]",
  "mainEntityOfPage" : {
    "@type" : "WebPage"
  },
  "name" : "How to use MongoDB in Laravel",
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://139767802.fs1.hubspotusercontent-eu1.net/hubfs/139767802/jaeves-logo-230917.png"
    },
    "name" : "Jaeves AI"
  },
  "text" : "In MySQL Database we stores the records in the form of rows and tables. But we need to define the structure of table and columns before inserting records. MySQL is quite slow in comparison to MongoDB while dealing with large databases. In this tutorial we will learn how to use mongodb in laravel. MongoDB represents data as JSON documents. In MongoDB we can do Real-time analytics, content management, internet of things, mobile apps. No schema definition required so lesser risk of attack due to design. It has the ability to handle large unstructured data. MongoDB uses JavaScript as query language. In MongoDB no restrictions on schema design. MongoDB has a pre-defined structure that can be defined and adhered to, but also, if you need different documents in a collection, it can have different structures. Using MongoDB with Laravel To use MongoDB in Laravel we will use Laravel MongoDB package. This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library extends the original Laravel classes, so it uses exactly the same methods. Installation We should have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php. We can use in Laravel 6 and above. Install the jenssegers/mongodb package via Composer composer require jenssegers/mongodb Now, add the service provider to config/app.php Jenssegers\\Mongodb\\MongodbServiceProvider::class, Laravel MongoDB Configuration Add a new mongodb connection to config/database.php 'mongodb' =&gt; [ 'driver' =&gt; 'mongodb', 'host' =&gt; env('DB_HOST', '127.0.0.1'), 'port' =&gt; env('DB_PORT', 27017), 'dsn' =&gt; env('DB_DSN'), 'database' =&gt; env('DB_DATABASE', 'homestead'), 'username' =&gt; env('DB_USERNAME', 'homestead'), 'password' =&gt; env('DB_PASSWORD', 'secret'), 'options' =&gt; [ // 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' =&gt; env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+ ], ], Create a Eloquent Model with MongoDB use Jenssegers\\Mongodb\\Eloquent\\Model; class Book extends Model { protected $collection = 'my_books_collection'; } 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'; } Using MongoDB in Laravel Authentication You need to replace the default Authenticatable class Illuminate\\Foundation\\Auth\\User with MongoDB Authenticatable Eloquent class Jenssegers\\Mongodb\\Auth\\User. use Jenssegers\\Mongodb\\Auth\\User as Authenticatable; class User extends Authenticatable { } MongoDB Query In Laravel // Mongo will also create _id, but the 'id' property will be used for primary key actions like find(). Book::create(['id' =&gt; 1, 'title' =&gt; 'The Fault in Our Stars']); Retrieving all models $users = User::all(); Retrieving a record by primary key $user = User::find('517c43667db388101e00000f'); Offset &amp; Limit (skip &amp; take) $users = User::skip(10) -&gt;take(5) -&gt;get(); The Original Author Package details is here. Also you can read about query and usage in details here. Recommendation Using MongoDB in Node.js How to validate form in ReactJS How to create charts in ReactJS Basic Query In MongoDB For more Mongodb Tutorials Click here, Node.js Tutorials Click here.",
  "url" : "https://jaeves.com/codelab/how-to-use-mongodb-in-laravel",
  "wordCount" : "904"
}
```

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Admin",
    "url" : "https://jaeves.com/codelab/author/admin"
  },
  "dateModified" : "2023-10-13T07:30:21.258Z",
  "datePublished" : "2023-10-02T22:32:54.000Z",
  "headline" : "How to use MongoDB in Laravel – Jaeves Codelab",
  "mainEntityOfPage" : {
    "@id" : "https://jaeves.com/codelab/how-to-use-mongodb-in-laravel",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://jaeves.com/hubfs/logo-2024-less-points.svg"
    },
    "name" : "Jaeves AI"
  }
}
```

```json
{
  "@context" : "http://schema.org",
  "@type" : "Organization",
  "description" : "Unlock the Power of AI for Content Creation. Explore Insights, Tips, and Trends on the Jaeves.com Blog. Empower Your Writing Journey Today!",
  "logo" : "https://jaeves.com/hubfs/untitled%20(4).png",
  "name" : "Jaeves AI",
  "sameAs" : [ "https://www.instagram.com/jaeves.ai", "https://www.linkedin.com/company/jaeves-ai", "https://www.youtube.com/@Jaeves_ai", "https://www.tiktok.com/@jaeves_ai" ],
  "url" : "https://jaeves.com"
}
```