Laravel CRUD With MongoDB Tutorial

Hello Artisan

In this brand new tutorial i am going to discuss about Laravel crud with mongoDB. In this laravel mongoDB crud example i will use jenssegers/mongodb Package. If You would like to get more details about the package, then Go To Github.

MongoDB is an open-source, cross-platform, document-oriented NoSQL database used for a large amount of data storage. In this laravel mongoDB crud operation tutorial i will separate it in two section. One is first setup mongoDB on system then i will start crud operation with mongoDB.

In this example i will simply create a animal model and then we will create crud operation on this animal route. Hope after finishing this project you will learn how to set up mongoDB with laravel in windows operating system and linux ubuntu operating system. 

 

Recommended : Laravel 7 CRUD ( Create , Read, Update, Delete) Example Tutorial

 

Setup MongoDB

In Windows

It is a common critical problem in this situation that first we need to set up mongoDB in our system. Happily, I have the best achievable solution for your system. So I will assist you to join your Laravel app to the MongoDB database quickly. Very first, you need to open this Link below.

 

https://pecl.php.net/package/mongodb/1.3.0/windows

 

Now, you have to download file according to your configuration. Extract and move the DLL Zip file into your PHP’s ext folder. The ext folder holds many DLL extensions files.

Now, you have to open the php.ini file and add or uncomment(remove #) the following line. To run with MongoDB, that driver requires to be bootstrap at the start of the server.

extension = php_mongodb.dll

Now, you have to save the file and restart your server to reflect your changes otherwise our changes will not apply. After that, you should be able to connect your MongoDB database to your PHP application, in our case application build with the Laravel.

 

In Ubuntu

In this case, we need to Install Mongo PECL extension and add in the PHP configuration(php.ini) file. which implements connectivity between PHP and MongoDB.

 

COMMAND
$ sudo pecl install mongo $ sudo echo "extension=mongo.so" >> /etc/php/7.1/apache2/php.ini

 

After establishing the extension, let’s restart apache service to reflect the changes.

command
$ sudo service apache2 restart

 

Finally, we are going to Configure and achieve our goal into Laravel Project. So now time to start our crud operation with mongoDB in laravel application. 

 

Step 1: Donwload Laravel

I am going to start from scratch so Install fresh Laravel Project by the writing following command.

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

 

Step 2 : Configure Database

Open .env file and adds the following details to configure the MongoDB Database.

.env

MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=mongoproject
MONGO_DB_USERNAME=SECRET
MONGO_DB_PASSWORD=SECRET

 

Next, we have to update on config >> database.php file as like below.

config/database.php

'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'  => []
        ],
    ]

 

Step 3: Install laravel-mongodb Package

In this step we need to install laravel-mongodb package via the Composer package manager, so one your terminal and fire bellow command:

composer require jenssegers/mongodb

 

Ok, after install package successfully, we will add service provider in app.php configuration file. So let's add as bellow:

config/app.php

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

 

Step 4: Create Animal Model

now we need to create Animal Model for connect with laravel eloquent. So let's create Animal model and put bellow code:

app/Animal.php


namespace App;

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

class Animal extends Eloquent
{
    protected $connection = 'mongoproject';
    protected $collection = 'animals';
    
    protected $fillable = [
        'species', 'color','leg'
    ];
}

 

Step 5:  Add Route

In this is step we need to add route for animal crud application. so open your "routes/web.php" file and add following route.

routes/web.php

Route::get('add','[email protected]');
Route::post('add','[email protected]');
Route::get('car','[email protected]');
Route::get('edit/{id}','[email protected]');
Route::post('edit/{id}','[email protected]');
Route::delete('{id}','[email protected]');

 

Step 6: Create AnimalController

Here, now we should create new controller as AnimalController. So run bellow command and create new controller.

php artisan make:controller AnimalController

 

So, let's copy bellow code and put on AnimalController.php file.

app/Http/Controllers/AnimalController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Animal;

class AnimalController extends Controller
{
    public function create()
    {
        return view('animalcreate');
    }
    public function store(Request $request)
    {
        $animal=new Animal();
        $animal->species = $request->get('species');
        $animal->color = $request->get('color');
        $animal->leg = $request->get('leg');        
        $animal->save();
        return redirect('animal')->with('success', 'Animal has been successfully added');
    }
    public function index()
    {
        $animals=Animal::all();
        return view('animalindex',compact('animals'));
    }
    public function edit($id)
    {
        $animal = Animal::find($id);
        return view('animaledit',compact('animal','id'));
    }
    public function update(Request $request, $id)
    {
        $animal= ANimal::find($id);
        $animal->species = $request->get('species');
        $animal->color = $request->get('color');
        $animal->leg = $request->get('leg');        
        $animal->save();
        return redirect('animal')->with('success', 'Animal has been successfully update');
    }
    public function destroy($id)
    {
        $animal = Animal::find($id);
        $animal->delete();
        return redirect('animal')->with('success','Animal has been  deleted');
    }
}

 

Step 7: Create Blade Files

Now everything are almost set to go. No we move in last step. In this step we have to create just blade files. Create some view file in resources >> views directory as like below and update with below code.

resources/views/animalcreate.blade.php

 

resources/views/animalindex.blade.php

 

resources/views/animaledit.blade.php

 

Now everything are set to go. Now visit this below url to check laravel mongoDB crud example ourput. 

url
 http://localhost:8000/animal

 

Read also : Laravel 7.x Rest API CRUD Example with JWT Auth

 

Hope it can help you.