Laravel Mongodb Integration
In this tech article we are going to integrate Laravel 8 with MongoDB and perform Auth and Basic CURD functionality. Laravel is a popular web development framework for PHP. It offers many defaults and provides a code structure that is easy to understand and quick to use for implementing web applications and APIs.
MongoDB’s document model makes it a great database choice for web applications because its flexible schema structure will easily evolve to meet your growing needs.
Prerequisites
- PHP 7.2 or PHP8 installed into your system.
- composer
- node JS
Steps To Follow:
- Install MongoDB
- Install MongoDB PHP Extension
- Create Fresh Laravel Application
- Config Laravel for MongoDB connection
- Creating Laravel Auth Functionality
- Creating basic CURD controller and view
- Conclusion
Show Video Tutorial On Youtube:
Step 1– Install Mongo DB
curl -fsSL https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add - sudo apt update sudo apt install mongodb
Step 2– Install the Laravel MongoDB PHP Extension
Before we can install the MongoDB libraries for Laravel, we need to install the PHP extension for MongoDB. Run the following command:
sudo pecl install mongodb
You will also need to ensure that the MongoDB extension is enabled in your php.ini file. The location of your php.ini file will vary depending on your operating system. Add the following line to your php.ini file:
extension="mongodb.so"
Now check your MongoDB status whether it’s running or not?
service mongodb status
Step 3– Install the Laravel Project
Once you have PHP and Composer installed, you can install Laravel. From a terminal window, enter the following command:
composer create-project laravel/laravel mongodb cd mongodb/ php artisan serve --host=0.0.0.0 --port=8000
Step 4–Configuring Your Laravel Project to Use MongoDB
Open .env
file from your laravel application directory and Configure MongoDB Database
DB_CONNECTION=mongodb DB_HOST=127.0.0.1 DB_PORT=27017 DB_DATABASE=myappdb DB_USERNAME= DB_PASSWORD=
In order for Laravel to communicate with your MongoDB database, you will need to add your database connection information to the config\database.php file under the “connections” object in your Laravel project as shown in this example:
'connections' => [..... ....... 'mongodb' => [ 'driver' => 'mongodb', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE', 'myappdb'), 'username' => env('DB_USERNAME', ''), 'password' => env('DB_PASSWORD', '') ], ........
Make sure to include the correct authentication information.
Set the default database connection name in config\database.php at top section
/* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mongodb'),
Define Providers:
In order to make connections with MongoDB you need Jenssegers Library:
composer require jenssegers/mongodb
If your Laravel project does not load dependencies automatically, you may also need to add the following to the provider’s section in your app.php file:
'providers' => [ /* * Laravel Framework Service Providers... */ Jenssegers\Mongodb\MongodbServiceProvider::class,
Step 5– Creating Laravel Auth Functionality
Now install auth functionality to your application, here I am going to use vue js framework for front end. So you can choose angular, react also
composer require laravel/ui php artisan ui vue --auth
You can see that authentication scaffolding generated. Also, you need to run the npm install and run dev in order to make it fully functional with compiling all js and CSS files. Npm stands for Node package manager It puts modules in place so that node can find them, and manages dependency conflicts intelligently. If npm not installed in your system then first install npm:
sudo apt install npm
Just go ahead and type npm install. It will install all required dependency script automatically.
npm install
After that use npm run dev command to compile all js and css file for your application.
npm run dev
Now finaly migurate your table to database
php artisan migrate
Change user model default authentication to Jenssegers MongoDB Authentication class at App\Models\User:
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Jenssegers\Mongodb\Auth\User as Authenticatable; //<--- Add This Line //use Illuminate\Foundation\Auth\User as Authenticatable; //--> Commentout this line use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable;
Step 6– Creating basic CURD controller and view
Crate model post with model and migration
php artisan make:model Post -mc
Creating Web Routs at Routs\web.php
Route::get('/post/{slug}', 'PostController@show'); Route::post('/post', 'PostController@store'); Route::get('/displayform', 'PostController@displayForm');
Edit Post Model as below:
use Jenssegers\Mongodb\Eloquent\Model; class Post extends Model { protected $connection = 'mongodb'; }
Add following function at Post Controller:
public function displayForm(){ return view('form'); } public function show($slug){ return view('post',['post'=>Post::where('slug','=', $slug)->first()]); } public function store(Request $request){ $post = new Post; $post->title = $request->title; $post->body = $request->body; $post->slug = $request->slug; $post->save(); return response()->json(["result" => "ok"], 201); } public function destroy($postId) { $post = Post::find($postId); $post->delete(); return response()->json(["result" => "ok"], 201); } public function update(Request $request, $postId) { $post = Post::find($postId); $post->title = $request->title; $post->body = $request->body; $post->slug = $request->slug; $post->save(); return response()->json(["result" => "ok"], 201); }
Add views form and post inside resourse directory:
resource\view\form.blade.php
<!DOCTYPE html> <html> <body> <h2>HTML Forms to test mongodb</h2> {!! Form::open(['route' => 'post', 'id' => 'action_form']) !!} <label for="fname">Title:</label><br> <input type="text" id="title" name="title" ><br> <label for="lname">body:</label><br> <input type="text" id="body" name="body" ><br><br> <label for="lname">slug:</label><br> <input type="text" id="slug" name="slug" ><br><br> <input type="submit" value="Submit"> {!! Form::close() !!} <p>If you click the "Submit" button, the form-data will be sent to mongodb".</p> </body> </html>
resource\view\post.blade.php
<!DOCTYPE html> <html> <head> <title>MyBlog</title> </head> <body> <h1>{{$post->title}}</h1> <div>{{$post->body}}</div> </body> </html>
Conclusion:
In this tutorial, we were able to connect a Laravel website to a MongoDB server. As we saw, the integration is simple and seamless.
Unlike relational databases like MySQL, you don’t need to worry about creating and maintaining database migrations. You can use the same Eloquent model functionality that you may already be familiar with. You can also take advantage of the additional querying capabilities that MongoDB provides.
Subroto Mondal
Latest posts by Subroto Mondal (see all)
- Installing and Configuring OpenShift: A Step-by-Step Guide for Linux Experts with Terminal Code - February 19, 2023
- Sed Command in Linux with Practical Examples - February 19, 2023
- Rsync Command uses with examples - February 19, 2023