Laravel MongoDB CRUD Operation Tutorial

To use Laravel with MongoDB, use the “jenssegers/mongodb” package.

Here is the step-by-step guide:

Step 1: Install Laravel Project

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

Step 2: Configure MongoDB Database

Let’s configure the MongoDB Database in our laravel application. So open the .env file and add the following details.

//.env

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

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

We will install the jenssegers/mongodb Package in our project.

composer require jenssegers/mongodb

Step 4: Define providers.

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

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

Step 5: Create a model

Use the Authenticatable model to create a crud application in Laravel with MongoDB. The User model extends an Authenticatable model. One of the big problems I encountered with MongoDB was when it was about the User. Unfortunately, MongoDB does not support the default model that Laravel offers, so we’ll have to use the one that comes with the package:

use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{
   //
}

If you want to use Laravel Passport with MongoDB, use the designmynight/laravel-mongodb-passport. It will provide you with another Authenticatable class that will do your job!

Type the following command in your terminal.

php artisan make:model Car 

It will create a Car.php file.

The 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'
    ];
}

SQL works with tables, and NoSQL works with collections. So instead of the $table variable, we’ll have a $collection variable.

Also, it’s essential to note that the primary key cannot be set through $primaryKey, and the $incrementing is unavailable.

Additionally, you might want to specify that the model belongs to the mongodb connection you created earlier.

You must be at peace that MongoDB auto-assigns primary keys to documents (the equivalent of rows from SQL). So, to access the primary key of a document, you have to use the same attribute name as in the basic model.

echo 'The Car ID is: '. $car->_id;
echo 'The Car ID is '. $car->id; // they both work

Using find() uses the primary key field to retrieve the result.

There are almost no schemas to define

In NoSQL, we don’t have schemas to define. So we can go as crazy as we want. But we can use the migrations to define indexes, unique fields, and other mongo-specific fields.

See the following code.

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

The migration process is the same. To run the migrations, ensure that the default driver set (the DB_CONNECTION env variable) is set to mongodb.

php artisan migrate

 In case you want to run both SQL and NoSQL in the same project, I can give you some hints:

  1. Move your SQL migrations to a folder inside the migrations folder. I’ll call it MySQL.
  2. All models that work with the default database driver should extend the right model.

Running migrations should be done locally or in production for the default driver (i.e., when DB_CONNECTION is set to mongodb).

For MySQL driver,

php artisan migrate --database=mysql --path=database/migrations/mysql/

As long as NoSQL is schemaless, we can define it while working with data. In MongoDB, we’re able to drop fields whenever we want. So, if we want to drop some fields, we can do it using the drop method.

$ppl = Employee::where('name', 'TrevorNoah')->first();
$ppl->drop('field1');

// or

$john->drop(['field1', 'field2']); // works with more

Let’s create a view file.

Step 6: Create a view file

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

<!-- 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 routes 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');
    }

Screenshot of HTML Form

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

For that front, we need to send the data to 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 and place the following code.

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

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

Create application of Laravel

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.

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

Make a caredit.blade.php file inside the 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 adding code to 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');
    }

Edit form in HTML

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

That’s it.

27 thoughts on “Laravel MongoDB CRUD Operation Tutorial”

  1. 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

    Reply
  2. 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

    Reply

Leave a Comment

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