Laravel 5 MongoDB CRUD Tutorial

Laravel 5 MongoDB CRUD Tutorial

In this post we will show you Laravel 5 MongoDB CRUD Tutorial, hear for Laravel 5 MongoDB CRUD Tutorial we will give you demo and example for implement.

Laravel is also more popular in today’s market. So in this tutorial, we 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, we 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.

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

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=3645
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' => [
		....
		Jenssegers\Mongodb\MongodbServiceProvider::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 Jenssegers\Mongodb\Eloquent\Model 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 App\Http\Controllers;
use App\Book;
use Illuminate\Http\Request;
class BookController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    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 \Illuminate\Http\Response
     */
    public function create()
    {
        return view('books.create');
    }
	
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    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  \App\Book  $book
     * @return \Illuminate\Http\Response
     */
    public function show(Book $book)
    {
        return view('books.show',compact('book'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Book  $book
     * @return \Illuminate\Http\Response
     */
    public function edit(Book $book)
    {
        return view('books.edit',compact('book'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Book  $book
     * @return \Illuminate\Http\Response
     */
    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  \App\Book  $book
     * @return \Illuminate\Http\Response
     */
    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 class="container">
    @yield('content')
</div>


</body>
</html>

resources/views/books/index.blade.php

@extends('books.layout')

@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Books</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('books.create') }}"> Create New Book</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>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 class="btn btn-info" href="{{ route('books.show',$book->id) }}">Show</a> 
                    <a class="btn btn-primary" href="{{ route('books.edit',$book->id) }}">Edit</a>
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
	        </td>
	    </tr>
	    @endforeach
    </table>

@endsection

resources/views/books/show.blade.php

@extends('books.layout')


@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Book</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('books.index') }}"> Back</a>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $book->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $book->detail }}
            </div>
        </div>
    </div>
@endsection

resources/views/books/create.blade.php

@extends('books.layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Add New Book</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('books.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if ($errors->any())
        <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

    <form action="{{ route('books.store') }}" method="POST">
    	@csrf
         <div class="row">
		    <div class="col-xs-12 col-sm-12 col-md-12">
		        <div class="form-group">
		            <strong>Name:</strong>
		            <input type="text" name="name" class="form-control" placeholder="Name">
		        </div>
		    </div>
		    <div class="col-xs-12 col-sm-12 col-md-12">
		        <div class="form-group">
		            <strong>Detail:</strong>
		            <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
		        </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

resources/views/books/edit.blade.php

[/php]

@extends('books.layout')

@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Book</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('books.index') }}"> Back</a>
            </div>
        </div>
    </div>
	
    @if ($errors->any())
        <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
    <form action="{{ route('books.update',$book->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>Name:</strong>
		            <input type="text" name="name" value="{{ $book->name }}" class="form-control" placeholder="Name">
		        </div>
		    </div>
		    <div class="col-xs-12 col-sm-12 col-md-12">
		        <div class="form-group">
		            <strong>Detail:</strong>
		            <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $book->detail }}</textarea>
		        </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

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:

Hope this code and post will helped you for implement Laravel 5 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 onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org

Leave a Comment

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

7  +  3  =  

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