Delete MongoDB Document using Laravel

Introduction

If you’re building web applications with the Laravel PHP web framework, you may want your app to interact with a MongoDB database. Fortunately, it’s easy to use Laravel to perform various database operations. In this article, we’ll explain how to delete a MongoDB document using Laravel.

Prerequisites

Before we move forward with our tutorial, let’s take a moment to review some of the key prerequisites needed for this project:

  • First, you’ll need to download and install Composer, which will help with installing Laravel and creating Laravel projects.
  • You’ll also need to download and install XAMMP and run it as a service.
  • You can use the text editor of your choice. Throughout this tutorial, we will be using Visual Studio Code as our text editor.
  • Be sure to download the compatible php_mongodb.dll for the installed PHP version on your system before completing this tutorial.
  • Be sure that MongoDB is properly installed and configured before proceeding.
  • In this article, the MongoDB version being used is:
db version v4.2.1
  • The PHP version being used is:
php 7.3.11
  • Finally, you’ll need to install the application Postman in order to follow along with this tutorial.

NOTE: In this article, we’ll be working in a Windows environment.

How to Configure MongoDB Database in PHP

Once all the required items have been installed, we can move forward with our project. We’ll start by configuring the MongoDB database to make it accessible to us when we start coding our Laravel application.

In the previous section, we mentioned that MongoDB must be downloaded and installed. Now, we’ll extract the DLL file in the following directory: C:\xampp\php\ext

We’ll need to register this DLL file within PHP as an extension. To do this, we’ll modify our php.ini file and append this text in the ‘extensions’ section: exetnsion=php_mongodb.dll.

Create Laravel Project

In this section, we’ll show you how to create a locally-hosted Laravel project.

Laravel projects can be created in the command prompt with the following Composer command:

NOTE: Be sure you’re in the xampp\htdocs directory when we executing this command.

composer create-project --prefer-dist laravel/laravel deletemongo

The code shown above creates the deletemongo directory inside htdocs.

We can test our Laravel project in the browser using the following URL: http://localhost/deletemongo/public.

The output should look like the following:

alt text

Configure MongoDB Database in Laravel

Next, we’ll configure Laravel to connect with our MongoDB database. We’ll need to modify two files for our database connection:

  • the .env file
DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=EmployeeDb
DB_USERNAME=
DB_PASSWORD=
  • the database.php file
 'mongodb' => [
            'driver'   => 'mongodb',
            'host'     => env('MONGO_DB_HOST', 'localhost'),
            'port'     => env('MONGO_DB_PORT', 27017),
            'database' => env('MONGO_DB_DATABASE','EmployeeDb'),
            'username' => env('MONGO_DB_USERNAME'),
            'password' => env('MONGO_DB_PASSWORD'),
            'options'  => []
        ],

NOTE: Remember to change the value of DB_CONNECTION from this:

'default' => env('DB_CONNECTION', 'mysql'),

to this:

'default' => env('DB_CONNECTION', 'mongodb').

Install MongoDB Package in Laravel

We can now install the MongoDB package using the following Composer command:

composer require jenssegers/mongodb

Register MongoDB Provider

To be able to register the MongodbServiceProvider within Laravel, we’ll need to add the following PHP script to our app.php file inside the config directory:

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

Create a Laravel Model

Our next step is to create a model for our application that will allow us to interact with our MongoDB database. To do this, we need to execute the following command within our project directory:

php artisan make:model Employee

The command shown above command creates a file called Employee.php. Within this file we can declare the MongoDB document field with which to perform our CRUD operations:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\ Model as Eloquent;

class Employee extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'employee';
   
    protected $fillable = [
        'name', 'age','department'
    ];
}

Creating a MongoDB Database and Collection

In this section, we’ll be creating a sample MongoDB database and collection that we can use in our code examples:

> use EmployeeDb
switched to db EmployeeDb
> db.employee.insertMany([{
... "name" : "James Stacey",
... "age" : 25,
... "department" : "Finance"
... },
... {
... "name" : "John Howard",
... "age" : 24,
... "department" : "Marketing"
... }]);
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5df5cfa8edf57fa3283a830d"),
                ObjectId("5df5cfa8edf57fa3283a830e")
        ]
}
>

After inserting the documents, we can verify that they’re in the collection:

> db.employee.find().pretty()
{
        "_id" : ObjectId("5df5da7eedf57fa3283a830f"),
        "name" : "James Stacey",
        "age" : 25,
        "department" : "Finance"
}
{
        "_id" : ObjectId("5df5da7eedf57fa3283a8310"),
        "name" : "John Howard",
        "age" : 24,
        "department" : "Marketing"
}

Deleting MongoDB Document using Laravel

In this section, we’ll show how to delete a MongoDB document by configuring the Laravel controller and the route.

Create and Configure Laravel Controller

Let’s configure the controller to be able to perform the delete operation:

  • First, we’ll create our controller by executing the following command:
php artisan make:controller EmployeeController

This command will create a PHP file called Employee.php. Then we’ll append the following PHP script to the file:

  public function destroy($id)
    {
        $pr = Employee::find($id);
        $pr->delete();

        return ('employee record has been successfully delete');
    }

Now we’ll need to configure the route where the user will send the delete request. To handle this, we’ll modify the file api.app in the routes directory with the following line of code:

Route::delete('/deleteEmployee/{id}', 'EmployeeController@destroy');

We can now test out our application using Postman. Our test will involve deleting a MongoDB document with an id of 5df5da7eedf57fa3283a830f:

alt text

We can also verify that our delete operation was successful using the Mongo shell:

> db.employee.find().pretty()
{
        "_id" : ObjectId("5df5da7eedf57fa3283a8310"),
        "name" : "John Howard",
        "age" : 24,
        "department" : "Marketing"
}
>

Conclusion

When you’re building apps with Laravel, it’s helpful to know how to perform various MongoDB operations such as deleting a MongoDB document. In this article, we provided step-by-step instructions for this process, showing you how to set up Laravel and perform a delete operation on a MongoDB document. With our examples to use as a guide, you’ll be able to incorporate MongoDB operations into your own Laravel development.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.