MongoDB with Laravel - Simple CRUD app
Tags: laravel, mongodb, webdev
Published: 2023-11-17 15:13:09

As per the [Laravel news](https://laravel-news.com/mongodb-laravel-integration), MongoDB support is official for Laravel.
This article provides a simplified and practical guide on building a REST API backend application with Laravel using MongoDB as the backend database. It is based on the original MongoDB article [here](https://www.MongoDB.com/developer/languages/php/laravel-MongoDB-tutorial/). This guide assumes you have PHP version 8.2 and a MongoDB Atlas cluster account. If you do not have a MongoDB Atlas cluster account, please follow the steps here:

- [create a cluster](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster/)
- [Sample Database](https://www.MongoDB.com/basics/sample-database)

**Prerequisites**:

- PHP version 8.2
- MongoDB Atlas cluster

**Setting up MongoDB support for Laravel Sail:**

The original article is not based on Laravel Sail, so if you are using Laravel Sail, follow these steps to install and configure MongoDB support for Laravel:

**_Update Dockerfile and composer.json files:_**

In the file _/vendor/laravel/sail/runtimes/8.2/Dockerfile_, add the package _php8.2-MongoDB_ to the line _RUN apt-get update_.

In the _composer.json_ file, add the line _"MongoDB/laravel-MongoDB": "4.0.0" _to the require section.

Run the command_ sail up _to install the necessary packages.

Once it is successful, create a new route to check PHPinfo 

 
```
Route::get('/info', function () {
    phpinfo();
});

```
 

![phpinfo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xemcx449g15mjqft4jaj.png)

and  access localhost/info.  You should see the MongoDB section.
 
Configure the config/database.php file to use MongoDB:

![MongoDBDSN](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7gbpt4794m12fgytpvq.png)

 
```
'connections' => [
        'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => env('MONGODB_URI'),
            'database' => 'sample_airbnb',
        ],

```
 
Ensure the **.env** file has the following line:

`MongoDB_URI=MongoDB+srv://username:password@demodb.adepp4p.MongoDB.net/?retryWrites=true&w=majority`

Replace username, password, and demodb.adepp4p.MongoDB.net with your MongoDB Atlas cluster information.

**Create models and controllers:**
Create a model named AirBnBs and a controller named AirBnBController.

The model file has the code as below

```

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
//use Illuminate\Database\Eloquent\Model;
use MongoDB\Laravel\Eloquent\Model;

class AirBnBs extends Model
{
    use HasFactory;

    protected $connection = 'mongodb';

    // equivalent to mySQL table    
    protected $collection = 'listingsAndReviews';
 

}

```


![Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdn8qhxnqx053rztwfvi.png)

**listingsAndReviews** is the name of the collection comes with demo database in Atlas Cluster.

**Check MongoDB connection:**
Create a route for ping and access _http://localhost/ping_. You should see a message if the connection is successful. If there is any error, check your MongoDB Atlas cluster and ensure your IP address is added for access.

**Implement CRUD operations:**
After establishing the connection, implement CRUD operations for the demo listings.

we have below routs 

```

Route::get('/ping',[AirBnBController::class, 'ping']);
Route::get('/list',[AirBnBController::class, 'getListing']);
Route::get('/update',[AirBnBController::class, 'updateListing']);
Route::get('/delete',[AirBnBController::class, 'deleteListing']);

```
![Routes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myeju0w453kimi83mbrr.png)

**Get listings:**
Create a route for getting listings with a condition to return fewer data. The condition selects listings with bedroom greater than or equal to 10. The corresponding MongoDB query is `{bedrooms: {$gte: 10}}.` The Eloquent query is `AirBnBs::where('bedrooms', '>=', 10)->get().`

So the code for get listing is 

![Listing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0gf21ixoafr2dzcgoegu.png)

``` 

public function getListing(Request $request)
    {
        $listing = AirBnBs::where('bedrooms', '>=', 10)->get();

        return  response()->json($listing);
    }

```

**Update listing:**
Create a route for updating a listing. Use the _id field as a unique identifier to update the name field.

```

  public function updateListing(Request $request)
    {   
        //important make sure it is a string, not an integer
        $item = '20958766';
        $name = 'Updated with Laravel Again and Again';

        try {
            $updateListing = AirBnBs::where('_id', $item)->update([
                'name' => $name
            ]);

            return ($updateListing == 1) ? "Successfully updated name $name" : "Failed to update";
        } catch (\Exception $e) {
            return 'Error: ' . $e->getMessage();
        }
    }

```

![update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7h5bomksifuondiehfs5.png)

**Delete listing:**

Create a route for deleting a listing. Use the _id field to delete the record.

```

  public function deleteListing(Request $request)
    {
        //important make sure it is a string, not an integer
        $item = '20701559';
        try {
            $result = AirBnBs::where('_id', '20701559')->delete();
            return ($result == 1)  ? "Successfully deleted the item $item " : "Failed to delete";

        } catch (\Exception $e) {
            return 'Error: ' . $e->getMessage();
        }
 
    }

```


![Delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8tx8vwws274dmzmmi20.png)

Conclusion:

This guide provides a basic example of implementing CRUD operations using Laravel and MongoDB. For more advanced features, please refer to the official MongoDB documentation.