Laravel 5.6 Mongodb crud tutorial with example for beginners – onlinecode
In this post we will give you information about Laravel 5.6 Mongodb crud tutorial with example for beginners – onlinecode. Hear we will give you detail about Laravel 5.6 Mongodb crud tutorial with example for beginners – onlinecodeAnd how to use it also give you demo for it if it is necessary.
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.
Step 1: Create MongoDB database
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" } )
Step 2: Install Laravel 5.6 Project
In this step, I will download the fresh Laravel application to start from the scratch.
composer create-project --prefer-dist laravel/laravel laravelmongodb
Step 3: Configure MongoDB Database
Now we will configure the database details to connect with MongoDB.
.env
MONGO_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' => [ .... JenssegersMongodbMongodbServiceProvider::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.
<!--?php
namespace App;
use JenssegersMongodbEloquentModel as Eloquent;
classCategoryextends Eloquent
{
protected$connection='mongodb';
protected$collection='categories';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected$fillable= [
'category', 'slug'
];
}
Step 6: Add Route
In this step, I will add a resource route for crud operation.
routes/web.php
Route::resource('categories','CategoryController');
Step 7: Add Category Controller
In this step, I will create a “CategoryController.php” file to perform crud action.
<!--?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppCategory;
classCategoryControllerextends Controller
{
publicfunctionindex()
{
$categories= Category::latest()->paginate(10);
return view('categories.index',compact('categories'))
->with('i', (request()->input('page', 1) -1) *5);
}
publicfunctioncreate()
{
return view('categories.create');
}
publicfunctionstore(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');
}
publicfunctionedit(Category $category)
{
return view('categories.edit',compact('category'));
}
publicfunctionupdate(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');
}
publicfunctiondestroy($id)
{
Category::destroy($id);
return redirect()->route('categories.index')
->with('success','Category deleted successfully');
}
}
Step 8: Create Blade View File
To perform the crud activity, I need below files :
- app.blade.php
- index.blade.php
- create.blade.php
- edit.blade.php
resources/views/layouts/app.blade.php
<!DOCTYPE html> <htmllang="en"> <head> <metacharset="utf-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width, initial-scale=1"> <title>Laravel 5.6 CRUD example with MongoDB</title> <linkhref="{{asset('css/app.css')}}"rel="stylesheet"> </head> <body> <divclass="container"> @yield('content') </div> </body> </html>
resources/views/categories/index.blade.php
@extends('layouts.app') @section('content') <divclass="row"> <divclass="col-lg-12 margin-tb"> <divclass="pull-left"> <h2>Category CRUD</h2> </div> <divclass="pull-right"> <aclass="btn btn-success"href="{{ route('categories.create') }}"> Create New Category</a> </div> </div> </div> @if ($message = Session::get('success')) <divclass="alert alert-success"> <p>{{ $message }}</p> </div> @endif <tableclass="table table-bordered"> <tr> <th>No</th> <th>Name</th> <th>Slug</th> <thwidth="280px">Operation</th> </tr> @foreach ($categories as $category) <tr> <td>{{ ++$i }}</td> <td>{{ $category->category}}</td> <td>{{ $category->slug}}</td> <td> <aclass="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') <buttontype="submit"class="btn btn-danger">Delete</button> </form> </td> </tr> @endforeach </table> {!! $categories->render() !!} @endsection
resources/views/categories/create.blade.php
@extends('layouts.app') @section('content') <divclass="row"> <divclass="col-lg-12 margin-tb"> <divclass="pull-left"> <h2>Add New Category</h2> </div> <divclass="pull-right"> <aclass="btn btn-primary"href="{{ route('categories.index') }}"> Back</a> </div> </div> </div> @if (count($errors) > 0) <divclass="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 <divclass="row"> <divclass="col-xs-12 col-sm-12 col-md-12"> <divclass="form-group"> <strong>Category Name:</strong> <inputtype="text"name="category"placeholder="Category Name"class="form-control"> </div> </div> <divclass="col-xs-12 col-sm-12 col-md-12 text-center"> <buttontype="submit"class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
resources/views/categories/edit.blade.php
@extends('layouts.app') @section('content') <divclass="row"> <divclass="col-lg-12 margin-tb"> <divclass="pull-left"> <h2>Update Category</h2> </div> <divclass="pull-right"> <aclass="btn btn-primary"href="{{ route('categories.index') }}"> Back</a> </div> </div> </div> @if (count($errors) > 0) <divclass="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') <divclass="row"> <divclass="col-xs-12 col-sm-12 col-md-12"> <divclass="form-group"> <strong>Category Name:</strong> <inputtype="text"name="category"value="{{$category->category}}"placeholder="Category Name"class="form-control"> </div> </div> <divclass="col-xs-12 col-sm-12 col-md-12 text-center"> <buttontype="submit"class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
If you will get “Class ‘MongoDBDriverManager’ not found” error then: Click here
Try this..
Hope this code and post will helped you for implement Laravel 5.6 Mongodb crud tutorial with example for beginners – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs