In this article we will see how to use MongoDB with Laravel (PHP framework). So first we need to install MongoDB and Laravel.

Laravel and MongoDB installation:

We will install Laravel and MongoDB one by one and I assume that you have PHP already installed with a web server.

Laravel Installation:

I assume LAMP environment is already configured. You can install Laravel simply through composer using following command if you have Composer already installed.

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

If you don’t know about composer or want to know more detailed installation and configuration of Larvel then Laravel documentation explained it in detail: http://laravel.com/docs/5.1#installation

MongoDB installation:

If you haven’t already installed MongoDB then MongoDB have separate guides for installing it own different Operating Systems. So check that: http://docs.mongodb.org/manual/installation/

Current version of MongoDB at this time is 3.x. But it you have MongoDB version 2.x installed and running on your machine then still feel free to use this tutorial, as it will work for 2.x as well and it have stuff related to 2.x difference in user creation section.

MongoDB driver for PHP:

PHP have official MongoDB driver that is called Mongo. It contains MongoClient class that is used by several packages which connect PHP with MongoDB.

You can install MongoDB driver on Windows OS using steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-windows

To install MongoDB driver on ubuntu  or other Linux distributions, follow steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-ubuntu

To check if MongoDB driver is successfully installed, try instantiating MongoClient class.

Laravel Package for MongoDB:

Laravel have several MongoDB related packages and some of them not work for Laravel 5.x (current versions at time of this writing). Based on several factors like number of contributers, number of commits, releases and documentation on github, simplicity and ease of use, I suggest using jenssegers/laravel-mongodb which is also knowns as Moloquent.

Installation:

To install for Laravel 5.1, install latest stable version using composer.

composer require jenssegers/mongodb

In config/app.php :

Add below line in providers array:

Jenssegers\Mongodb\MongodbServiceProvider::class,

And add in same file, add below line in aliases array:

'Moloquent' => 'Jenssegers\Mongodb\Model',

Moloquent Configurations:

In app/config/database.php, add MongoDB connection detail:

'mongodb' => array(
'driver' => 'mongodb',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE', 'l5'),
'username' => env('DB_USERNAME', 'l5'),
'password' => env('DB_PASSWORD', '123456'),
'options' => array(
'db' => 'admin' // sets the authentication database required by mongo 3
)
),

and make this mongodb connection, default connection.

'default' => env('DB_CONNECTION', 'mongodb'),

If you have installed MongoDB just now then you will not have Database, username and password to provide in connection info. For that purpose you need to first create database, username and password.

Setting up MongoDB Database and User:

To create a MongoDB database, you need to start, execute “mongo” from command line. To do so you need to add MongoDB bin directory to your system path. And then run:

mongod

This will run mongo server to listen calls.

In case you see error like: “ data/db not found ” , then that means that this path doesn’t exist on your system or don’t have appropriate permissions. So either create and assign appropriate permissions at that location or with appropriate permissions create DB data folder at some other custom location and give DB path like:

mongod --dbpath custom/directory/path

Once it is running, mongo server will be listening for client calls. So you need to run mongo shell client by simply opening another shell instance and run :

mongo

This will open mongoDB shell.

Creating Database in MongoDB:

Using mongo client shell, you need to create your database

> use dbname
> db.insert({"key":"value"})
By executing above statement, use statement switches DB to “dbname”, and assigns value “dbname” to variable “db”  so you can use your desired DB name. If “dbname” is name of existing database then it will switch to that database or else it will create that Database if atleast one record is added to that database.

Setting up First User and access:

If you are using Mongo 3.0 or above, first of all you need to switch to “admin” database and creating a user with administrative rights for all databases.

> use admin
> db.createUser(
{
user: "siteUserAdmin",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
You can replace “siteUserAdmin” and “password” from above code with your desired admin username and password. Role “userAdminAnyDatabase” is a special role for administrating all databases and this role is at “admin” database.

Once you have this Admin user on admin DB, you need to create user for your required DB, in our case “dbname”.

> use records
> db.createUser(
{
user: "recordsUserAdmin",
pwd: "password",
roles: [ { role: "userAdmin", db: "records" } ]
}
)

Here you can replace “recordsUserAdmin”,”password” and “dbname” with desired username, password and your intended database name. And this will set your admin user for that database.

If you are using MongoDB version 2.x then user creation is different. In version 2.x db.createUser() function is not present. You need to use db.addUser() like:

> use products
> db.addUser( { user: "user1",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
} )

So now you have DBname, username and password to put in you Laravel app/config/database.php

Extending Models from Moloquent:

Only thing that is left is to extend your models from “Moloquent” instead of “Eloquent”.  So a typical model will look like this:

<?php
namespace App\Models; use Moloquent; /**
* Category Model
*
* @author Hafiz Waheeduddin
*/
class Category extends Moloquent
{
public function tasks()
{
return $this->hasMany('App\Models\Task', 'category_id');
}
}

So after that you can simply run most of queries of query builder through category model. And can utilized ORM in similar way as Moloquent supports many types of relationships, so you can utilize them too.

Moloquent Detail and Documentation:

Moloquent have very good examples at github to understand it and use it. So for Moloquent usage, reference and understanding, please check moloquent github page .

laravel 连接mongodb的更多相关文章

  1. nodejs连接mongodb的方法

    一. var express = require('express'); var mongodb = require('mongodb'); var app = express(); app.use( ...

  2. Nodejs开发(2.连接MongoDB)

    一.先配置MongoDB Win10下下载那个安装版,zip版的会报却各种DLL,安装在你希望的路径,实在安装错了,就剪切过来也行(本例E:\mongodb). 然后是配置启动脚本,就是写一个bat文 ...

  3. 在express中使用Mongoose连接MongoDB

    为何要学Mongoose? Mongoose是MongoDB的一个对象模型工具,封装了MongoDB对文档的的一些增删改查等常用方法,让NodeJS操作Mongodb数据库变得更加灵活简单. 0.安装 ...

  4. java连接mongodb的一个奇葩问题及奇葩解决方式

    昨天在eclipse中编写代码,本来连接mongodb进行各项操作都是正常的,但是有一会儿突然之间就没法连接了,还一直抱错,错误如下: 信息: Cluster created with setting ...

  5. Java 连接MongoDB

    1.驱动 通过java连接MongoDB需要一个java版的驱动 下载地址:http://mongodb.github.io/mongo-java-driver/ 2.连接MongoDB 通过 com ...

  6. 远程连接mongodb出现 no route to host 和 Connection refused

    部署好mongodb服务器后,在客户端安装好php的mongodb扩展,用程序连接mongodb服务器出错:no route to host.搜索了差不多一天的时候都没有相关的解决方法.最后在mong ...

  7. NOSQL Mongo入门学习笔记 - C++连接Mongodb(三)

    OS环境: Centos 7.1 release X86_64 编译环境: G++ 4.8.3 已经成功搭建好了Mongodb,也初步在命令行中的查询与写入数据的基本方法,现在通过C++来连接Mong ...

  8. 【mongodb 学习一】环境搭建之 mac 下连接 mongodb 的UI 客户端

    记录下 mongodb 的学习 懒得自己达 mongodb 的服务器了 虽然一句命令就能搞定了 brew install mongodb 可是考虑到以后的应用还是放在网上的,就直接用现成的服务吧 下载 ...

  9. NodeJS连接MongoDB数据库时报错

    今天第一次尝试连接MongoDB数据库,具体步骤也很简单. 首先,通过NodeJS运行环境安装MongoDB包,进入要安装的目录,执行语句 npm install mongodb 安装成功后,通过如下 ...

随机推荐

  1. keychain实现ssh对秘钥免登陆免输入密码

    Linux同一网段实现密码认证,管理. 项目:https://github.com/funtoo/keychain 01.生成秘钥 ssh-keygen -t rsa   #  -t rsa | ds ...

  2. 从零开始的 Python 爬虫速成指南

    序 本文主要内容:以最短的时间写一个最简单的爬虫,可以抓取论坛的帖子标题和帖子内容. 本文受众:没写过爬虫的萌新. 入门 0.准备工作 需要准备的东西: Python.scrapy.一个IDE或者随便 ...

  3. MySQL插入性能优化

    目录 MySQL插入性能优化 代码优化 values 多个 一个事务 插入字段尽量少,尽量用默认值 关闭 unique_checks bulk_insert_buffer_size 配置优化 inno ...

  4. iOS 关于 设计模式 与网友讨论实录

    关于 设计模式 与网友讨论实录 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留 ...

  5. php 第三方DB库NOTORM

    百度NOTORM找到该库的官网 :http://www.notorm.com/ 打开E:\AppServ\php7\php.ini 找到extension=php_pdo_mysql.dll 解开前面 ...

  6. ubuntu14.4开启ftp服务

    1 更新源列表 打开"终端窗口",输入"sudo apt-get update"-->回车-->"输入当前登录用户的管理员密码" ...

  7. unity, shader input and output

    http://wiki.unity3d.com/index.php?title=Shader_Code

  8. Android开发14——监听内容提供者ContentProvider的数据变化

    一.提出需求 有A,B,C三个应用,B中的数据需要被共享,所以B中定义了内容提供者ContentProvider:A应用修改了B应用的数据,插入了一条数据.有这样一个需求,此时C应用需要得到数据被修改 ...

  9. [hihoCoder] #1081 : 最短路径·一

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 万圣节的早上,小Hi和小Ho在经历了一个小时的争论后,终于决定了如何度过这样有意义的一天——他们决定去闯鬼屋! 在鬼屋门口 ...

  10. Linux 共享库(动态库)

    Linux 系统上有两类根本不同的 Linux 可执行程序.第一类是静态链接的可执行程序.静态可执行程序包含执行所需的所有函数 — 换句话说,它们是“完整的”.因为这一原因,静态可执行程序不依赖任何外 ...