Laravel – MongoDB CRUD Tutorial

Laravel – MongoDB CRUD Tutorial

In this post we will give you information about Laravel – MongoDB CRUD Tutorial. Hear we will give you detail about Laravel – MongoDB CRUD TutorialAnd how to use it also give you demo for it if it is necessary.

today, most of the developer choose mongodb as database, because it takes less memory to store data and the very simple way we can use it. Laravel is also more popular in today’s market. So in this tutorial, I would like to share with you Laravel 5.6 with MongoDB CRUD operation. here we will use mongodb as database and create insert update delete and view of books with Laravel 5.6.

We will use “jenssegers/laravel-mongodb” composer package for creating CRUD(create read update and delete). using this package we can use collection, where, first, all, get, take, orWhere, whereIn, whereBetween, whereNull, orderBy, skip, distinct etc eloquent method of model.

In this example, i will create mongodb database with “books” collection. then we will configuration of mongodb database details on env file. then we will create CRUD module with Laravel 5.6 application. So just follow bellow step and get layout like as bellow screenshot.

Preview:

Step 1: Create MongoDB database

in first step, we need to create mongodb database and books collection. So successful MongoDB installation open the terminal, connect to MongoDB, create a database and collection and insert a books like as bellow command.

mongo

> use hddatabase

> db.books.insert( { "name": "laravel", "detail": "test" } )

Step 2: Install Laravel 5.6 Project

we are going to from scratch so, we need to get fresh Laravel 5.6 application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Also see:Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.

Step 3: MongoDB Database Configuration

After complete installation, we will make database mongodb configuration for example database name, username, password etc for our crud application of laravel 5.6. So let’s open .env file and fill all details like as bellow:

.env

MONGO_DB_HOST=127.0.0.1

MONGO_DB_PORT=27017

MONGO_DB_DATABASE=hddatabase

MONGO_DB_USERNAME=

MONGO_DB_PASSWORD=

Now we need to add array details on database.php config file. so let’s add this way:

config/database.php

<?php


return [


....

'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 we need to install laravel-mongodb package via the Composer package manager, so one your terminal and fire bellow command:

composer require jenssegers/mongodb

Ok, after install package successfully, we will add service provider in app.php configuration file. So let’s add as bellow:

config/app.php

<?php


return [

....

'providers' => [

....

JenssegersMongodbMongodbServiceProvider::class,

]

.....

]

Step 5: Create books Model

now we need to create Book Model for connect with laravel eloquent. So let’s create Book model and put bellow code:

app/Book.php

<?php


namespace App;


use JenssegersMongodbEloquentModel as Eloquent;


class Book extends Eloquent

{

protected $connection = 'mongodb';

protected $collection = 'books';


/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'detail'

];

}

Step 6: Add Resource Route

In this is step we need to add resource route for book crud application. so open your “routes/web.php” file and add following route.

routes/web.php

Route::resource('books','BookController');


Step 7: Create BookController

Here, now we should create new controller as BookController. So run bellow command and create new controller. bellow controller for create resource controller.

php artisan make:controller BookController --resource --model=Book

After bellow command you will find new file in this path “app/Http/Controllers/BookController.php”.

In this controller will create seven methods by default as bellow methods:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

So, let’s copy bellow code and put on BookController.php file.

app/Http/Controllers/BookController.php

<?php


namespace AppHttpControllers;


use AppBook;

use IlluminateHttpRequest;


class BookController extends Controller

{

/**

* Display a listing of the resource.

*

* @return IlluminateHttpResponse

*/

public function index()

{

$books = Book::all();

return view('books.index',compact('books'))

->with('i', (request()->input('page', 1) - 1) * 5);

}


/**

* Show the form for creating a new resource.

*

* @return IlluminateHttpResponse

*/

public function create()

{

return view('books.create');

}


/**

* Store a newly created resource in storage.

*

* @param IlluminateHttpRequest $request

* @return IlluminateHttpResponse

*/

public function store(Request $request)

{

request()->validate([

'name' => 'required',

'detail' => 'required',

]);


Book::create($request->all());


return redirect()->route('books.index')

->with('success','Book created successfully.');

}


/**

* Display the specified resource.

*

* @param AppBook $book

* @return IlluminateHttpResponse

*/

public function show(Book $book)

{

return view('books.show',compact('book'));

}


/**

* Show the form for editing the specified resource.

*

* @param AppBook $book

* @return IlluminateHttpResponse

*/

public function edit(Book $book)

{

return view('books.edit',compact('book'));

}


/**

* Update the specified resource in storage.

*

* @param IlluminateHttpRequest $request

* @param AppBook $book

* @return IlluminateHttpResponse

*/

public function update(Request $request, Book $book)

{

request()->validate([

'name' => 'required',

'detail' => 'required',

]);


$book->update($request->all());


return redirect()->route('books.index')

->with('success','Book updated successfully');

}

/**

* Remove the specified resource from storage.

*

* @param AppBook $book

* @return IlluminateHttpResponse

*/

public function destroy(Book $book)

{

$book->delete();


return redirect()->route('books.index')

->with('success','Book deleted successfully');

}

}

Step 8: Create Blade Files

now we move in last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder “books” then create blade files of crud app. So finally you have to create following bellow blade file:

1) layout.blade.php

2) index.blade.php

3) show.blade.php

4) form.blade.php

5) create.blade.php

6) edit.blade.php

So let’s just create following file and put bellow code.

resources/views/books/layout.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 5.6 CRUD Application</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">

</head>

<body>


<div >

@yield('content')

</div>


</body>

</html>

resources/views/books/index.blade.php

@extends('books.layout')


@section('content')

<div >

<div >

<div >

<h2>Books</h2>

</div>

<div >

<a href="{{ route('books.create') }}"> Create New Book</a>

</div>

</div>

</div>


@if ($message = Session::get('success'))

<div >

<p>{{ $message }}</p>

</div>

@endif


<table >

<tr>

<th>No</th>

<th>Name</th>

<th>Details</th>

<th width="280px">Action</th>

</tr>

@foreach ($books as $book)

<tr>

<td>{{ ++$i }}</td>

<td>{{ $book->name }}</td>

<td>{{ $book->detail }}</td>

<td>

<form action="{{ route('books.destroy',$book->id) }}" method="POST">

<a href="{{ route('books.show',$book->id) }}">Show</a>

<a href="{{ route('books.edit',$book->id) }}">Edit</a>

@csrf

@method('DELETE')

<button type="submit" >Delete</button>

</form>

</td>

</tr>

@endforeach

</table>


@endsection

resources/views/books/show.blade.php

@extends('books.layout')


@section('content')

<div >

<div >

<div >

<h2> Show Book</h2>

</div>

<div >

<a href="{{ route('books.index') }}"> Back</a>

</div>

</div>

</div>


<div >

<div >

<div >

<strong>Name:</strong>

{{ $book->name }}

</div>

</div>

<div >

<div >

<strong>Details:</strong>

{{ $book->detail }}

</div>

</div>

</div>

@endsection

resources/views/books/create.blade.php

@extends('books.layout')


@section('content')

<div >

<div >

<div >

<h2>Add New Book</h2>

</div>

<div >

<a href="{{ route('books.index') }}"> Back</a>

</div>

</div>

</div>


@if ($errors->any())

<div >

<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


<form action="{{ route('books.store') }}" method="POST">

@csrf


<div >

<div >

<div >

<strong>Name:</strong>

<input type="text" name="name" placeholder="Name">

</div>

</div>

<div >

<div >

<strong>Detail:</strong>

<textarea style="height:150px" name="detail" placeholder="Detail"></textarea>

</div>

</div>

<div >

<button type="submit" >Submit</button>

</div>

</div>


</form>


@endsection

resources/views/books/edit.blade.php

@extends('books.layout')


@section('content')

<div >

<div >

<div >

<h2>Edit Book</h2>

</div>

<div >

<a href="{{ route('books.index') }}"> Back</a>

</div>

</div>

</div>


@if ($errors->any())

<div >

<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


<form action="{{ route('books.update',$book->id) }}" method="POST">

@csrf

@method('PUT')


<div >

<div >

<div >

<strong>Name:</strong>

<input type="text" name="name" value="{{ $book->name }}" placeholder="Name">

</div>

</div>

<div >

<div >

<strong>Detail:</strong>

<textarea style="height:150px" name="detail" placeholder="Detail">{{ $book->detail }}</textarea>

</div>

</div>

<div >

<button type="submit" >Submit</button>

</div>

</div>


</form>


@endsection

Now we are ready to run our crud application example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

Also see:Laravel 5.6 CRUD Application for Starter

http://localhost:8000/books

I hope it can help you…

Hope this code and post will helped you for implement Laravel – MongoDB CRUD Tutorial. 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

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

11  +    =  12

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US