AppDividend
Latest Code Tutorials

Laravel MongoDB CRUD Example | Laravel With NoSQL

25

Laravel MongoDB CRUD Example is the topic, we will discuss today. In this example, we will use jenssegers/mongodb Package. If You need to get more information, then Go To Github. MongoDB is an open-source, cross-platform, document-oriented NoSQL database used for high volume data storage. MongoDB is written in C++. Let’s outline our whole blog post.

#How To Use Laravel With MongoDB

  • Step 1: Configure the Mongodb database in Windows.
  • Step 2: Install and configure Laravel.
  • Step 3: Install and configure the MongoDB package for Laravel.
  • Step 4: Create a model, route, controller, and view file.
  • Step 5: From the view file, fill the input details and send the POST request to the Laravel server which then saves the data into MongoDB database.
  • Step 6: Display the data in the frontend using the Laravel view.
  • Step 7: Then create an edit form and update the data into the database.
  • Step 8: Write the logic to delete the data from the database inside the controller file.

Okay, let’s go through the above steps one by one.

#Configure the Mongodb database in Windows

If you are connecting MongoDB database to Laravel or any PHP application, then you might face one issue, and that is PHP MongoDB driver.

The package, we will install in Laravel requires php mongodb driver installs on our machine. But if you try to download a direct package without installing the driver, then you will face an error that says that you have one extension missing in your PHP extension files or other errors depending on your configured environment.

It is the most critical issue in this scenario. Luckily I have the best possible solution for you. So I will help you to connect your Laravel application to MongoDB database. So first, you need to go to this Link. I am assuming that you are using Windows.

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

Now, right now, I am using Windows 10 32Bit OS, and my PHP version is 7.1. So you will choose the download file based on your machine configuration.

mongodb driver

Download the DLL Zip file and extract it inside your PHP’s ext directory. That ext directory contains many DLL extensions files already.

I am using XAMPP so, your directory path to the ext is C:\xampp\php\ext. The DLL file name of MongoDB driver is  php_mongodb.dll. So make sure that this file is installed correctly in the ext directory.

Now, open the php.ini file and add the following line. If the line is already there, then check if it is commented or not, if commented, then remove the semicolon to uncomment. To work with MongoDB, this driver needs to be bootstrap at the start of the server.

extension=php_mongodb.dll

Save that file.

Please restart the server. It is essential; otherwise, our changes will not reflect.

Now, you will be able to connect your PHP application to the MongoDB database. In our case, it is the Laravel MongoDB connection. Now, we will be ready to start our Laravel MongoDB CRUD Tutorial With Example.

Laravel MongoDB CRUD

We are going to Configure Laravel Project.

Step 1: Install Laravel Project

Download New Laravel Project by the writing following command.

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

Step 2: Configure MongoDB Database

So now, let’s configure the MongoDB Database in our laravel application. So open .env file add the following detail.

//.env

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

Next, we want to add a new mongodb connection on config >> database.php file.

//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

Now we will install jenssegers/mongodb Package in our project.

composer require jenssegers/mongodb

Step 4: Define providers

Find the providers in config >> app.php file and register the MongodbServiceProvider.

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

Step 5: Create a model

Type the following command in your terminal.

php artisan make:model Car

It will create a Car.php file.

Package includes a MongoDB enabled Eloquent class that you can use to establish models for corresponding collections. Add the code in the Car.php file.

//Car.php

<?php

namespace App;

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

class Car extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'cars';
    
    protected $fillable = [
        'carcompany', 'model','price'
    ];
}

Step 6: Create a view file

Create a file in resources  >>  views  >>   carcreate.blade.php and put this following code in it.

<!-- carcreate.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel MongoDB CRUD Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  </head>
  <body>
    <div class="container">
      <h2>Laravel MongoDB CRUD Tutorial With Example</h2><br/>
      <div class="container">
    </div>
      <form method="post" action="{{url('add')}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Carcompany">Car Company:</label>
            <input type="text" class="form-control" name="carcompany">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Model">Model:</label>
            <input type="text" class="form-control" name="model">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Price">Price:</label>
            <input type="text" class="form-control" name="price">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
   </div>
  </body>
</html>

Step 7: Create one controller and route

php artisan make:controller CarController

It will create a controller file called CarController.php.

We register route in routes  >>  web.php file. So let us do it.

//web.php

Route::get('add','CarController@create');
Route::post('add','CarController@store');
Route::get('car','CarController@index');
Route::get('edit/{id}','CarController@edit');
Route::post('edit/{id}','CarController@update');
Route::delete('{id}','CarController@destroy');

Add code to create() function to display view.

//CarController.php

public function create()
    {
        return view('carcreate');
    }

 Step 8: Save Data into MongoDB Database

We need to code the store function to save the data in the database.

//CarController.php

use App\Car;

   public function store(Request $request)
    {
        $car = new Car();
        $car->carcompany = $request->get('carcompany');
        $car->model = $request->get('model');
        $car->price = $request->get('price');        
        $car->save();
        return redirect('car')->with('success', 'Car has been successfully added');
    }

Laravel MongoDB CRUD Tutorial

Step 9: Make an index page to list the car information

For that, frontend, we need to send the data to the carindex.blade.php. So, in the CarController.php file, we need to write the code to get the data and return it to the index view.

//PostController.php

public function index()
    {
        $cars=Car::all();
        return view('carindex',compact('cars'));
    }

In resources >> views create a different blade file called carindex.blade.php file and place the following code in it.

<!-- carindex.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index Page</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
    <br />
    @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Company</th>
        <th>Model</th>
        <th>Price</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      
      @foreach($cars as $car)
      <tr>
        <td>{{$car->id}}</td>
        <td>{{$car->carcompany}}</td>
        <td>{{$car->model}}</td>
        <td>{{$car->price}}</td>
        <td><a href="{{action('CarController@edit', $car->id)}}" class="btn btn-warning">Edit</a></td>
        <td>
          <form action="{{action('CarController@destroy', $car->id)}}" method="post">
            @csrf
            <input name="_method" type="hidden" value="DELETE">
            <button class="btn btn-danger" type="submit">Delete</button>
          </form>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
  </body>
</html>

So, if you type the URL: http://localhost:8000/car, you can see the page like the below image.

Laravel MongoDB CRUD Example

Step 10: Build an edit view for updating the Car                Information

The next step will be to call the edit function in the CarController.php file and add the following code to it.

public function edit($id)
    {
        $car = Car::find($id);
        return view('caredit',compact('car','id'));
    }

Now, make a caredit.blade.php file inside resources  >>  views folder.

<!-- caredit.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel MongoDB CRUD Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  </head>
  <body>
    <div class="container">
      <h2>Edit A Form</h2><br/>
      <div class="container">
    </div>
      <form method="post" action="{{action('CarController@update', $id)}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Carcompany">Car Company:</label>
            <input type="text" class="form-control" name="carcompany" value="{{$car->carcompany}}">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Model">Model:</label>
            <input type="text" class="form-control" name="model" value="{{$car->model}}">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Price">Price:</label>
            <input type="text" class="form-control" name="price" value="{{$car->price}}">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Update</button>
          </div>
        </div>
      </form>
   </div>
  </body>
</html>

The next move will be to add some code in the update() function.

//CarController.php

public function update(Request $request, $id)
    {
        $car= Car::find($id);
        $car->carcompany = $request->get('carcompany');
        $car->model = $request->get('model');
        $car->price = $request->get('price');        
        $car->save();
        return redirect('car')->with('success', 'Car has been successfully update');
    }

laravel mongodb tutorial

Step 11: Delete the Car Information

//CarController.php

public function destroy($id)
    {
        $car = Car::find($id);
        $car->delete();
        return redirect('car')->with('success','Car has been  deleted');
    }

The final Code of CarController.php looks like the below code.

//CarController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Car;

class CarController extends Controller
{
    public function create()
    {
        return view('carcreate');
    }
    public function store(Request $request)
    {
        $car=new Car();
        $car->carcompany = $request->get('carcompany');
        $car->model = $request->get('model');
        $car->price = $request->get('price');        
        $car->save();
        return redirect('car')->with('success', 'Car has been successfully added');
    }
    public function index()
    {
        $cars=Car::all();
        return view('carindex',compact('cars'));
    }
    public function edit($id)
    {
        $car = Car::find($id);
        return view('caredit',compact('car','id'));
    }
    public function update(Request $request, $id)
    {
        $car= Car::find($id);
        $car->carcompany = $request->get('carcompany');
        $car->model = $request->get('model');
        $car->price = $request->get('price');        
        $car->save();
        return redirect('car')->with('success', 'Car has been successfully update');
    }
    public function destroy($id)
    {
        $car = Car::find($id);
        $car->delete();
        return redirect('car')->with('success','Car has been  deleted');
    }
}

Finally, Our Laravel MongoDB CRUD Tutorial With Example is over. Thanks for taking it.

Recommended Posts

Laravel Vue Example

Laravel CRUD Example

Laravel Angular Example

Laravel React Example

25 Comments
  1. Amalendu kar says

    Thank you so much..

  2. Pawan sai says

    Which one will be the default page.

  3. Ahmad says

    thank you so much. this helps a lot

  4. Ankit says

    Thanks… It really helps.

  5. Shasi Kanth Dulipalla says

    Very useful tutorial… thanks a lot for sharing..

  6. james says

    Thanks so much for this

  7. Alaa says

    very useful and simple tutorial

  8. sepehr says

    very useful

  9. Vaibhav Nadgonde says

    any idea how to configure laravel with mongo on ubuntu18.04?

  10. Jalal says

    “Class ‘MongoDB\Driver\Manager’ not found”

    1. Mateus says

      Could you fix the issue about “Class ‘MongoDB\Driver\Manager’ not found”?
      I’m having the same problem here

  11. mohamed ramdan says

    perfect thanks for this

  12. Bai MaoLi says

    Great tutorial for beginner
    Thanks.

  13. Brenda Perez says

    Thank you so much

  14. gio says

    thanks a lot for sharing.. 😀

  15. Ken says

    Thanks , works smoothly

  16. Jose says

    Hi, I’m following the steps for the installation but when the jenssegers component was installed it gives me this error:

    Warning: PHP Startup: Unable to load dynamic library ‘C:/laragon/bin/php/php-7.1.12-Win32-VC14-x64/ext\php_mongodb.dll’ – No se puede encontrar el modulo especificado.

    I think it’s the route he’s using \ and not /
    but I’m not sure and if that is not how to solve it.
    I am sure that if the corresponding dll is in the correct one, if you could help me Thanks
    I’m using w10 64, laravel 5.6

  17. nilesh dabhi says

    thank you

  18. fogang says

    thank you so much

  19. moinkhan says

    which version of mongodb you shoud be used?

    1. kabil says

      Please use version 1.6; when i used version 1.3 it throws me error

  20. sunny says

    Call to a member function prepare() on null

  21. Sanjeet says

    Even after following the steps there will be configuration issue,
    Just type following command before proceeding the steps
    1. # sudo apt install php-pear
    2. #sudo apt install php-dev
    3. #sudo pecl install mongodb
    Add a small code in .ini file (directory:Computer/etc/php/ph7.2/apache2/.ini) i’e

    extension=mongodb.so

    4. #sudo phpenmod mongodb

  22. Galang Yoga says

    How to User::find() on nested collection ?

  23. Deepraj says

    how t use where condition instead of find() .. such as Car::where(‘model’,220)->get(); …. its giving me empty array.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.