Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] "Laravel 8 with Mongodb Tutorial"

Thursday 18 February 2021
|
Read: Completed in minutes

[Tips] "Laravel 8 with Mongodb Tutorial"

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: https://localhost/dashboard/phpinfo.php

"Laravel 8 with Mongodb Tutorial"


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

"Laravel 8 with Mongodb Tutorial" - Webzone Tech Tips Zidane

- Copy  php_mongodb.dll and php_mongodb.pdb files to PHP extension file directory ...\PHPTutorial\php\php-7.4.5\ext.
- 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

"Laravel 8 with Mongodb Tutorial" - Webzone Tech Tips Zidane

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
        [
		....
		Jenssegers\Mongodb\MongodbServiceProvider::class,
	]
	.....
]
?>  
  

Step 4: Add Router:

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


use App\Http\Controllers\StudentController;

Route::resource('student',StudentController::class);
  
Step 5: Create Model and Controller

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

Model: Student.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
// use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model;        // 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  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        //
        return view('student.view',compact('student'));
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    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  \App\Student  $student
     * @return \Illuminate\Http\Response
     */
    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>

"Laravel 8 with Mongodb Tutorial" - Webzone Tech Tips Zidane


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 

Remember change all: 

// use Illuminate\Database\Eloquent\Model;
to => use Jenssegers\Mongodb\Eloquent\Model;  on the model

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

Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about "Laravel 8 with Mongodb Tutorial" , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips, all things Tech Tips for web development  - I am Zidane, See you next time soon ✋✋✋✋

🙇🏼🙇🏼 Your Feedback Is Valuable and Helpful to Us - Webzone, all things Tech Tips web development Zidane
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com