DEV Community

Cover image for MongoDB with Laravel - Simple CRUD app
Jeevachaithanyan Sivanandan
Jeevachaithanyan Sivanandan

Posted on

MongoDB with Laravel - Simple CRUD app

As per the Laravel news, 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. 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:

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();
});

Enter fullscreen mode Exit fullscreen mode

phpinfo

and access localhost/info. You should see the MongoDB section.

Configure the config/database.php file to use MongoDB:

MongoDBDSN

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

Enter fullscreen mode Exit fullscreen mode

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';


}

Enter fullscreen mode Exit fullscreen mode

Model

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']);

Enter fullscreen mode Exit fullscreen mode

Routes

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


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

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

Enter fullscreen mode Exit fullscreen mode

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();
        }
    }

Enter fullscreen mode Exit fullscreen mode

update

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();
        }

    }

Enter fullscreen mode Exit fullscreen mode

Delete

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.

Top comments (5)

Collapse
 
gbhorwood profile image
grant horwood

i enjoyed this, but wish the code examples had been copyable text rather than screen shots.

Collapse
 
jeevanizm profile image
Jeevachaithanyan Sivanandan

thanks for the like. In the case of code examples, I read somewhere that typing the actual code by looking at the code screenshot does help better than just copy pasting.

From my experience it is true.

Collapse
 
jeevanizm profile image
Jeevachaithanyan Sivanandan

@gbhorwood I have updated the article with copyable code, hope that works for you

Collapse
 
kwnaidoo profile image
Kevin Naidoo

Interesting article! I have a slightly dated project, initially, this library was a bit limited with more advanced queries. Had to implement my own adapter, but seems like it's matured now.

Collapse
 
jeevanizm profile image
Jeevachaithanyan Sivanandan

it is now officially supported. please see the link