Laravel - MongoDB connection
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.Here we will see how to use mongodb as database with Laravel.
We will use jenssegers/laravel-mongodb composer package.
In this example, i will create mongodb database with "students" collection. then we will configuration of mongodb database details on env file.
- Create MongoDB database
In first step, we need to create mongodb database and students collection. So successful MongoDB installation open the terminal, connect to MongoDB, create a database and collection and insert a students like as bellow command.
mongo
> use class
> db.students.insert( { "name": "jaydeep", "detail": "test" } )
- MongoDB Database Configuration
After complete installation, we will make database mongodb configuration for example database name, username, password etc. So let's open .env file and fill all details like as bellow:
MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=class
MONGO_DB_USERNAME=
MONGO_DB_PASSWORD=
Now we need to add array details on database.php config file:
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' => []
],
]
]
- Install laravel-mongodb Package
In this step we need to install laravel-mongodb package via the Composer package manager, so open your terminal and fire bellow command:
composer require jenssegers/mongodb
after install package successfully, we will add service provider in app.php configuration file.
config/app.php
<?php
return [
'providers' => [
Jenssegers\Mongodb\MongodbServiceProvider::class,
]
]
I hope it can help you.
Comments
Post a Comment