[Tips] [Laravel-MongoDB] Laravel 8 with Mongodb Tutorial

0
38

Hello everyone, Hope you well

If you wanna find the PHP framework working with NOSQL, (Mongodb). Laravel is the best solution for you. (Laravel at current version is 8 now). So I will show you how to connect Laravel 8 with MongoDB at this time.

Step 0: Install MongoDB, MongoDB PHP 

Step 1: Install Laravel 8

Step 2: Configure MongoDB database

Step 3: Install laravel-mongodb Package

Step 4: Add Route

Step 5: Create Model and Controller

Step 6: Create Blade Files 

—————————–

First Step: Step MongoDB Shell: by this link

This is MongoDB shell (server)

NextL Setup MongoDB PHP. if you use XAMPP,  you can follow me (similar with MAPP, etc, …)

First check your PHP Version by type url: http://localhost/dashboard/phpinfo.php

After found your architecture, and php version; we go to this link for get mongodb-dll

– Copy  php_mongodb.dll and php_mongodb.pdb files to PHP extension file directory …PHPTutorialphpphp-7.4.5ext.
– Edit the php.ini file and add extension=php_mongodb.dll to it.
– Restart XAMPP

– After setup succeed pls check below url and see the result like that

Step 1: Now start create Laravel project by command 


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

Step 2: Config MongoDB connection. (At .env file)


MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=mongoproject
MONGO_DB_USERNAME=
MONGO_DB_PASSWORD=

Now, we have to add a connection array of MongoDB in the config/database.php file.


'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


composer require jenssegers/mongodb


After the install the package We will add below providers in the config/app.php file.

<?php
     [
....
JenssegersMongodbMongodbServiceProvider::class,
]
.....
]
?>

Step 4: Add Router:

We have to need put below the student resource route in routes/web.php


use AppHttpControllersStudentController;

Route::resource('student',StudentController::class);

Step 5: Create Model and Controller


php artisan make:controller StudentController --resource --model=Student

Model: Student.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
// use IlluminateDatabaseEloquentModel;
use JenssegersMongodbEloquentModel;        // use this, this is very important!!!

class Student extends Model
{
use HasFactory;

protected $connection = 'mongodb';
protected $collection = 'students';
protected $fillable = [
'first_name', 'last_name', 'address',
];
}

Model: StudentController.php


validate([
'txtFirstName'=>'required',
'txtLastName'=> 'required',
'txtAddress' => 'required'
]);

$student = new Student([
'first_name' => $request->get('txtFirstName'),
'last_name'=> $request->get('txtLastName'),
'address'=> $request->get('txtAddress')
]);

$student->save();
return redirect('/student')->with('success', 'Student has been added');
}

/**
* Display the specified resource.
*
* @param AppStudent $student
* @return IlluminateHttpResponse
*/
public function show(Student $student)
{
//
return view('student.view',compact('student'));
}

/**
* Show the form for editing the specified resource.
*
* @param AppStudent $student
* @return IlluminateHttpResponse
*/
public function edit(Student $student)
{
//
return view('student.edit',compact('student'));
}

/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param AppStudent $student
* @return IlluminateHttpResponse
*/
public function update(Request $request,$id)
{
//

$request->validate([
'txtFirstName'=>'required',
'txtLastName'=> 'required',
'txtAddress' => 'required'
]);


$student = Student::find($id);
$student->first_name = $request->get('txtFirstName');
$student->last_name = $request->get('txtLastName');
$student->address = $request->get('txtAddress');

$student->update();

return redirect('/student')->with('success', 'Student updated successfully');
}

/**
* Remove the specified resource from storage.
*
* @param AppStudent $student
* @return IlluminateHttpResponse
*/
public function destroy(Student $student)
{
//
$student->delete();
return redirect('/student')->with('success', 'Student deleted successfully');
}
}
?>


Step 6: Create Blade Files

Finally, we will create the layout.blade.php files and the second time we will create list.blade.php, create.blade.php, view.blade.php, and edit.blade.php in “resources/views/student/” directory.


<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8"></meta>
<meta content="width=device-width, initial-scale=1" name="viewport"></meta>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>


list.blade.php

@extends('student.layout')

@section('content')
<div class="row">
<div class="col-lg-11">
<h2>Laravel 8 Mongodb CRUD Tutorial Example</h2>
</div>
<div class="col-lg-1">
<a class="btn btn-success" href="{{ route('student.create') }}">Add</a>
</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>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th width="280px">Action</th>
</tr>
@php
$i = 0;
@endphp
@foreach ($students as $student)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $student->first_name }}</td>
<td>{{ $student->last_name }}</td>
<td>{{ $student->address }}</td>
<td>
<form action="{{ route('student.destroy',$student->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('student.show',$student->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('student.edit',$student->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection


create.blade.php

@extends('student.layout')

@section('content')
<div class="row">
<div class="col-lg-11">
<h2>Add New Student</h2>
</div>
<div class="col-lg-1">
<a class="btn btn-primary" href="{{ url('student') }}"> Back</a>
</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('student.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="txtFirstName">First Name:</label>
<input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
</div>
<div class="form-group">
<label for="txtLastName">Last Name:</label>
<input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
</div>
<div class="form-group">
<label for="txtAddress">Address:</label>
<textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
@endsection

edit.blade.php

@extends('student.layout')

@section('content')
<div class="row">
<div class="col-lg-11">
<h2>Update Student</h2>
</div>
<div class="col-lg-1">
<a class="btn btn-primary" href="{{ url('student') }}"> Back</a>
</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 method="post" action="{{ route('student.update',$student->id) }}" >
@method('PATCH')
@csrf
<div class="form-group">
<label for="txtFirstName">First Name:</label>
<input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName" value="{{ $student->first_name }}">
</div>
<div class="form-group">
<label for="txtLastName">Last Name:</label>
<input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName" value="{{ $student->last_name }}">
</div>
<div class="form-group">
<label for="txtAddress">Address:</label>
<textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address">{{ $student->address }}</textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
@endsection


view.blade.php

@extends('student.layout')

@section('content')
<div class="row">
<div class="col-lg-11">
<h2>Laravel 8 CRUD Example</h2>
</div>
<div class="col-lg-1">
<a class="btn btn-primary" href="{{ url('student') }}"> Back</a>
</div>
</div>
<table class="table table-bordered">
<tr>
<th>First Name:</th>
<td>{{ $student->first_name }}</td>
</tr>
<tr>
<th>Last Name:</th>
<td>{{ $student->first_name }}</td>
</tr>
<tr>
<th>Address:</th>
<td>{{ $student->address }}</td>
</tr>

</table>
@endsection


You will get some authentication problem for MongoDB 

Remmember change all: 

// use IlluminateDatabaseEloquentModel;
to => use JenssegersMongodbEloquentModel;  on the model

If you cannot do it on the tutorial you can download my github source code here.

Any feedback, you can leave your comment here

Zidane