How to use MongoDB in Laravel
Tags: mongodb, laravel, webdev, beginners
Published: 2022-03-06 18:01:04

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
```ssh
composer require jenssegers/mongodb
```
Now, add the service provider to config/app.php
```php
Jenssegers\Mongodb\MongodbServiceProvider::class,
```

## Laravel MongoDB Configuration
Add a new mongodb connection to config/database.php
```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
```php
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.
```php
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.
```php
use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{

}
```

## MongoDB Query In Laravel
```php
// 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
```php
$users = User::all();
```

## Retrieving a record by primary key
```php
$user = User::find('517c43667db388101e00000f');
```

## Offset & Limit (skip & take)
```php
$users = User::skip(10)
        ->take(5)
        ->get();
```
You can read the author package details and [usage details here.](https://github.com/jenssegers/laravel-mongodb#eloquent)

Please like share and give positive feedback to motivate me to write more.

For more tutorials [visit my website](https://www.w3courses.org/tutorials/).
Thanks:)
Happy Coding:)