Laravel CRUD With MongoDB

Advertisements

In this blog, we will use jenssegers/mongodb Package. If You want 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. MongoDB is written in C++. 

Configure the MongoDB

You might have to face one issue to connect Laravel or any other PHP application with MongoDB, and that is PHP MongoDB driver.

Advertisements

We have to install the package in Laravel requires PHP MongoDB driver installs on our machine. But if you attempt to download the package directly without installing the driver, then you will encounter an error that shows that you have one extension missing in your PHP extension files or other errors depending on your configured conditions.

In Windows

It is a common critical problem in this situation. Happily, I have the best achievable solution for you. So I will assist you to join your Laravel app to the MongoDB database. Very first, you need to open this Link.

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

Now, 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, 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.

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

$ sudo service apache2 restart

Laravel MongoDB CRUD

Finally, we are going to Configure and achieve our goal into Laravel Project.

Step 1: Install Laravel Project

Install fresh Laravel Project by the writing following command.

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

For more information please visit the official Laravel doc.

Step 2: Configure MongoDB 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 add a new MongoDB configuration 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 Laravel project.

composer require jenssegers/mongodb

Step 4: Add providers

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

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

Step 5: Create a new model

You can create a model manually too but here we are creating it through the command line.

php artisan make:model Animal

It will create Animal.php file into the app directory.

The package automatically includes a MongoDB enabled Eloquent class that you can use to establish models for corresponding collections. Add the code in the Animal.php file.

//Animal.php

<?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 6: Create a view file

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

<!-- animalcreate.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="Species">Species:</label>
            <input type="text" class="form-control" name="species">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Color">Color:</label>
            <input type="text" class="form-control" name="color">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Leg">Leg:</label>
            <input type="text" class="form-control" name="leg">
          </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 a controller and route

php artisan make:controller AnimalController

It will create a controller file called AnimalController.php  into app >> app >> Http >> Controllers.

We have to register our routes in routes >> web.php file.

//web.php

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

Now create view function in AnimalController.php to show add form in the browser.

//AnimalController.php

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

 Step 8: Save Data into MongoDB Database

Now we need to create the store function to insert the data in the database.

//AnimalController.php

use App\Animal;

   public function store(Request $request)
    {
        $animal = new Animal();
        $animal->carcompany = $request->get('carcompany');
        $animal->model = $request->get('model');
        $animal->price = $request->get('price');        
        $animal->save();
        return redirect('animal')->with('success', 'Animal has been successfully added');
    }
Laravel CRUD With MongoDB 1

Step 9: Make a view page to list the animal information

For that, view, we need to transfer the data to the animalindex.blade.php. So, in the AnimalController.php file, we need to add the code to get the data and pass it to the index view.

//AnimalController.php

public function index()
{
    $animal=Animal::all();
    return view('animalindex',compact('animals'));
}

To display all animals list, we have to create a new view called animalindex.blade.php and place the following code in it.

<!-- animalindex.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>Species</th>
        <th>Color</th>
        <th>Leg</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      
      @foreach($animals as $animal)
      <tr>
        <td>{{$animal->id}}</td>
        <td>{{$animal->species}}</td>
        <td>{{$animal->color}}</td>
        <td>{{$animal->leg}}</td>
        <td><a href="{{action('AnimalController@edit', $animal->id)}}" class="btn btn-warning">Edit</a></td>
        <td>
          <form action="{{action('AnimalController@destroy', $animal->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>

Now, open the URL: http://localhost:8000/animal, you can see all the details in the table.

Step 10: Create an edit form for updating the Animal Information

Add the following code into AnimalController.php.

//AnimalController.php


public function edit($id)
{
    $animal = Animal::find($id);
    return view('animaledit',compact('animal','id'));
}

Next, create an animaledit.blade.php file inside resources >> views folder.

<!-- animaledit.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('AnimalController@update', $id)}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Animalcompany">Animal Company:</label>
            <input type="text" class="form-control" name="species" value="{{$animal->species}}">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Color">Color:</label>
            <input type="text" class="form-control" name="color" value="{{$animal->color}}">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Leg">Leg:</label>
            <input type="text" class="form-control" name="leg" value="{{$animal->leg}}">
          </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>

Now, add update() function in AnimalController.php.

//AnimalController.php

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

Step 11: Add Delete functionality for Animal Information

//AnimalController.php

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

The final Code of CarController.php will be looks like the following code.

//AnimalController.php

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