Laravel Simple CRUD with MongoDB

Category
Tutorial
Reading
5 mins
Views
2.3K
Posting
11 Sep 2023

Databases are a very important place to store data, and there may be many options available, such as MySQL, PostgreSQL, SQL Server, MongoDB, etc. In this opportunity, we will discuss how to integrate an application based on the Laravel framework with MongoDB as a data storage or database. MongoDB is an open-source application that focuses on document-oriented or NoSQL databases that are suitable for storing high-volume data.

MongoDB may not be as popular to use in the Laravel environment, website owners may prefer MySQL as a data storage place, but MongoDB is more popular to use in the NodeJS environment. But if you are looking for information on how to connect MongoDB to your Laravel, we will discuss it here.

 

Laravel Simple CRUD with MongoDB - Genelify

 

 

1. How to connect MongoDB with Laravel

There are various ways to connect Laravel with MongoDB, using the library from mongodb/laravel-mongodb. Before entering the core tutorial, you need to prepare some components that are required, which is configuring the MongoDB database in your Windows platform, by activating the driver on MongoDB. And you can also manually download the MongoDB package for Windows by visiting the following link: https://pecl.php.net/package/mongodb/1.3.0/windows.

Download and extract the zip file, then copy and paste all the .dll files into the ext directory in your webserver. If you are using XAMPP, you can copy and paste the files into the directory C:\xampp\php\ext. Make sure the php_mongodb.dll file is stored in the directory.

After that, you can open the php.ini file and add a few lines, such as extension=php_mongodb.dll, but if the extension=php_mongodb.dll is already in the php.ini file, please remove the semicolon to activate MongoDB, then save and restart your webserver.

Now that you can use MongoDB as a database in the Laravel environment, you can install and configure it in the Laravel framework.

 

2. Installing the Laravel framework

To connect MongoDB to the Laravel environment, you need to install an additional library to make it easier to manage. First, you install the Laravel framework with the command:

composer create-project --prefer-dist laravel/laravel laravel-mongo-crud

and install the required library:

composer require mongodb/laravel-mongodb

Wait for the installation process to finish, after that, you can go to the next configuration, which is setting up or configuring the MongoDB database.

 

3. Configuring MongoDB in Laravel

After the installation process is complete, the next step is to set the host name, port, username, and other settings in the .env file. For the database name, just adjust it to your project, such as:

MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=mongolaracrud
MONGO_DB_USERNAME=
MONGO_DB_PASSWORD=

Next, to activate MongoDB itself, you need to enter some commands in the database.php file to connect to the .env file.

'connections' => [
    ...
    'mongodb' => [
        'driver'   => 'mongodb',
        'host'     => env('MONGO_DB_HOST', 'localhost'),
        'port'     => env('MONGO_DB_PORT', 27017),
        'database' => env('MONGO_DB_DATABASE'),
        'username' => env('MONGO_DB_USERNAME'),
        'password' => env('MONGO_DB_PASSWORD'),
        'options'  => []
    ],
]

 

4. Defining a new provider in Laravel configuration

Because we have installed additional libraries to activate the MongoDB database, you need to register the MongodbServiceProvider in the app.php file in the config folder. Open the config folder, then find app.php, open it, and add some lines of code in the following section:

'providers' => [
    MongoDB\Laravel\MongoDBServiceProvider::class,
],

 

5. Integrating MongoDB into the Model

Assuming you already have a model or are creating a model file, to connect it to MongoDB, you need to add the namespace of the library that has been installed, such as:

use MongoDB\Laravel\Eloquent\Model;

As an example, you have a Books.php file.

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class Books extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'books';
    
    protected $fillable = [
        'name', 'type', 'price'
    ];
}

SQL works with tables, while NoSQL works with collections. So that MongoDB works properly, we added the $connection variable. It should be noted that primary keys cannot be set through $primaryKey, and auto-incrementing is not provided. But don't worry, MongoDB will automatically set primary keys for your database document. To access primary keys, you must use the same attribute name as in the basic model, for example:

echo 'ID book: ' . $book->id;
// or
echo 'ID book: ' . $book->_id;

Use find() method to use the primary key and get the result. In NoSQL, it usually does not have a schema to be defined, but we can use and take advantage of migrations to determine indexes, unique fields, and other MongoDB fields.

Schema::create('books', function ($collection) {
    $collection->index('blabla');
    $collection->unique('blabla');
});

To run migrations, make sure the default driver is set to MongoDB in the DB_CONNECTION variable on .env file.

php artisan migrate

 

6. Store Data

We need some code to set data storage in the database, for example:

public function store(Request $request)
{
    $book = new Books();
    $book->name = $request->get('name');
    $book->type = $request->get('type');
    $book->price = $request->get('price');        
    $book->save();

    return redirect('index')->with('success', 'Book is successfully added!');
}

 

7. Read Data

To display data using MongoDB, you use the all method, for example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Books;

class BooksController
{
    public function index()
    {
        $books = Books::all();
        return view('index', compact('books'));
    }

    public function getBookById($id)
    {
        $books = Books::find($id);
        return view('index', compact('books'));
    }

    // Create method
    // Update method
    // Delete method
}

And display the book variable into the view as usual:

@foreach($books as $book)
<tr>
    <td>{{ $book->id }}</td>
    <td>{{ $book->name }}</td>
    <td>{{ $book->type }}</td>
    <td>{{ $book->price }}</td>
</tr>
@endforeach

 

8. Update or edit data

If you need a feature to change data, you can add a new function to manage the data that will be changed, for example:

public function edit($id)
{
    $books = Books::find($id);
    return view('book_edit', compact('cars', 'id'));
}

Next, just set the data in your Laravel view file as desired. Next, you can create a new function to handle the data and insert it into the database.

public function update(Request $request, $id)
{
    $book= Books::find($id);
    $book->name = $request->get('name');
    $book->type = $request->get('type');
    $book->price = $request->get('price');        
    $book->save();
    return redirect('index')->with('success', 'Book is successfully updated!');
}

 

9. Deleting data

To create a delete feature is not too difficult, you just need to add a delete method, for example:

public function destroy($id)
{
    $book = Books::find($id);
    $book->delete();
    return redirect('index')->with('success', 'Book is successfully deleted!');
}

 

10. Define route

So that CRUD can be used, next you need routing settings for each method created, each route adapted to its respective function and use, an index method for displaying data, a store method for storing data, an update method for making data changes and a delete method. to delete the requested data. The following is the contents of the code that you can use:

use App\Http\Controllers\BooksController;

....
Route::get('books', [BooksController::class, 'index']);
Route::get('books/{id}', [BooksController::class, 'getBookById']);
Route::post('book/store', [BooksController::class, 'store']);
Route::post('book/update/{id}', [BooksController::class, 'update']);
Route::get('book/delete/{id}', [BooksController::class, 'delete']);
....

 

Conclusion

MongoDB is highly recommended for handling high traffic, as it has been proven to be fast and reliable. On average, MongoDB consumes 4GB of RAM with 600 million documents with methods such as read, write, and delete. However, it should be noted not to use caching as it can cause data accumulation in memory, which can slow down the application. If your application is already uploaded to the hosting, you should activate the mongodb extension in the php extension in the panel.

Share