MongoDB is an open-source, cross-platform, document-oriented NoSQL database used for high volume data storage. MongoDB is written in C++.
Using MongoDB with Laravel, We can use same eloquent functionality such as : first, all, get, take, skip, where, orWhere, whereIn, whereBetween, whereNull, orderBy, distinct etc.
In this Laravel MongoDB Tutorial, You will learn how to fetch records, insert, edit and delete the records.
For this example, I have used jenssegers/mongodb
Package.
I assume that you have installed and configured mongodb database. You can also install mongodb by clicking the Install MongoDB Enterprise on Ubuntu.
Type mongo on the terminal to start with MongoDB shell.
>mongo
You will get following message on screen :
MongoDB shell version v3.6.5 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.6.5 Welcome to the MongoDB shell.
MongoDB Enterprise > use demodatabase switched to db demodatabase db.categories.insert( { "category": "PHP Tutorials", "slug": "php-tutorials" } )
In this step, I will download the fresh Laravel application to start from the scratch.
composer create-project --prefer-dist laravel/laravel laravelmongodbStep 3: Configure MongoDB Database
Now we will configure the database details to connect with MongoDB.
.envMONGO_DB_HOST=127.0.0.1 MONGO_DB_PORT=27017 MONGO_DB_DATABASE=demodatabase MONGO_DB_USERNAME= MONGO_DB_PASSWORD=
Now we need to add array connection details on database.php config file. so let's add this way:
.... '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 4: Install Laravel MongoDB Package
In this step, I will install the jenssegers/mongodb
package in our application.
composer require jenssegers/mongodb
Now register the MongodbServiceProvider in app.php within config directory.
.... 'providers' => [ .... Jenssegers\Mongodb\MongodbServiceProvider::class, ] .....Step 5: Create a Model
In this step, I will create a model by running following command :
php artisan make:model Category
Now update the "Model.php" with following line of code to establish models for corresponding collections.
namespace App;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Category extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'categories';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'category', 'slug'
];
}
In this step, I will add a resource route for crud operation.
routes/web.phpRoute::resource('categories','CategoryController');Step 7: Add Category Controller
In this step, I will create a "CategoryController.php" file to perform crud action.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::latest()->paginate(10);
return view('categories.index',compact('categories'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('categories.create');
}
public function store(Request $request)
{
request()->validate([
'category' => 'required'
]);
$slug=str_slug($request->category);
Category::create($request->all()+['slug'=>$slug]);
return redirect()->route('categories.index')
->with('success','Category created successfully');
}
public function edit(Category $category)
{
return view('categories.edit',compact('category'));
}
public function update(Request $request,Category $category)
{
request()->validate([
'category' => 'required'
]);
$slug=str_slug($request->category);
$category->update($request->all()+['slug'=>$slug]);
return redirect()->route('categories.index')
->with('success','Category updated successfully');
}
public function destroy($id)
{
Category::destroy($id);
return redirect()->route('categories.index')
->with('success','Category deleted successfully');
}
}
To perform the crud activity, I need below files :
- app.blade.php
- index.blade.php
- create.blade.php
- edit.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel 5.6 CRUD example with MongoDB</title> <link href="{{asset('css/app.css')}}" rel="stylesheet"> </head> <body> <div class="container"> @yield('content') </div> </body> </html>
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Category CRUD</h2> </div> <div class="pull-right"> <a class="btn btn-success" href="{{ route('categories.create') }}"> Create New Category</a> </div> </div> </div> @if ($message = Session::get('success')) <div class="alert alert-success"> <p>{{ $message }}</p> </div> @endif <table class="table table-bordered"> <tr> <th>No</th> <th>Name</th> <th>Slug</th> <th width="280px">Operation</th> </tr> @foreach ($categories as $category) <tr> <td>{{ ++$i }}</td> <td>{{ $category->category}}</td> <td>{{ $category->slug}}</td> <td> <a class="btn btn-primary" href="{{ route('categories.edit',$category->id) }}">Edit</a> <formaction="{{ route('categories.destroy',$category->id) }}" method="POST" style='display:inline'> @csrf @method('DELETE') <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> @endforeach </table> {!! $categories->render() !!} @endsection
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Add New Category</h2> </div> <div class="pull-right"> <a class="btn btn-primary" href="{{ route('categories.index') }}"> Back</a> </div> </div> </div> @if (count($errors) > 0) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <formaction="{{ route('categories.store') }}" method="POST"> @csrf <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Category Name:</strong> <input type="text" name="category" placeholder="Category Name" class="form-control"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
@extends('layouts.app') @section('content') <div class="row"> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Update Category</h2> </div> <div class="pull-right"> <a class="btn btn-primary" href="{{ route('categories.index') }}"> Back</a> </div> </div> </div> @if (count($errors) > 0) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <formaction="{{ route('categories.update',$category->id) }}" method="POST"> @csrf @method('PUT') <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Category Name:</strong> <input type="text" name="category" value="{{$category->category}}" placeholder="Category Name" class="form-control"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
If you will get "Class 'MongoDB\Driver\Manager' not found" error then: Click here