laravel 连接mongodb
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的更多相关文章
- nodejs连接mongodb的方法
一. var express = require('express'); var mongodb = require('mongodb'); var app = express(); app.use( ...
- Nodejs开发(2.连接MongoDB)
一.先配置MongoDB Win10下下载那个安装版,zip版的会报却各种DLL,安装在你希望的路径,实在安装错了,就剪切过来也行(本例E:\mongodb). 然后是配置启动脚本,就是写一个bat文 ...
- 在express中使用Mongoose连接MongoDB
为何要学Mongoose? Mongoose是MongoDB的一个对象模型工具,封装了MongoDB对文档的的一些增删改查等常用方法,让NodeJS操作Mongodb数据库变得更加灵活简单. 0.安装 ...
- java连接mongodb的一个奇葩问题及奇葩解决方式
昨天在eclipse中编写代码,本来连接mongodb进行各项操作都是正常的,但是有一会儿突然之间就没法连接了,还一直抱错,错误如下: 信息: Cluster created with setting ...
- Java 连接MongoDB
1.驱动 通过java连接MongoDB需要一个java版的驱动 下载地址:http://mongodb.github.io/mongo-java-driver/ 2.连接MongoDB 通过 com ...
- 远程连接mongodb出现 no route to host 和 Connection refused
部署好mongodb服务器后,在客户端安装好php的mongodb扩展,用程序连接mongodb服务器出错:no route to host.搜索了差不多一天的时候都没有相关的解决方法.最后在mong ...
- NOSQL Mongo入门学习笔记 - C++连接Mongodb(三)
OS环境: Centos 7.1 release X86_64 编译环境: G++ 4.8.3 已经成功搭建好了Mongodb,也初步在命令行中的查询与写入数据的基本方法,现在通过C++来连接Mong ...
- 【mongodb 学习一】环境搭建之 mac 下连接 mongodb 的UI 客户端
记录下 mongodb 的学习 懒得自己达 mongodb 的服务器了 虽然一句命令就能搞定了 brew install mongodb 可是考虑到以后的应用还是放在网上的,就直接用现成的服务吧 下载 ...
- NodeJS连接MongoDB数据库时报错
今天第一次尝试连接MongoDB数据库,具体步骤也很简单. 首先,通过NodeJS运行环境安装MongoDB包,进入要安装的目录,执行语句 npm install mongodb 安装成功后,通过如下 ...
随机推荐
- Eclipse集成ijkplayer并实现本地和网络视频播放等
概述 Eclipse 集成ijkplayer demo,播放本地视频.和rtmp流. 详细 代码下载:http://www.demodashi.com/demo/10630.html 原文地址:Ecl ...
- Swift代理造成内存泄漏的解决办法
在swift中,使用代理 ,可能很多人会这样实现: .首先定义一份协议. protocol ToolProrocol{ //代理方法 func didRecieveResults(result:Int ...
- JavaScript 设计模式之命令模式
一.命令模式概念解读 1.命令模式概念文字解读 命令模式(Command)的定义是:用来对方法调用进行参数化处理和传送,经过这样处理过的方法调用可以在任何需要的时候执行.也就是说该模式旨在将函数的调用 ...
- WordPress网站搬家的问题
老邢的博客搬家全过程(wordpress搬家知识总结) 网站搬家过程中的几个问题 WordPress网站搬家的方法 WORDPRESS.ORG - zh-cn:WordPress 博客搬家 ...
- 深入理解Java:自定义java注解
要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解: 元注解的作用就是负责注解其他注解.Java5. ...
- 工作总结 public DateTime? CollectionTime 可空类型 Code First
数据库生成就对应生成 可以为空 的字段
- Linux系统休眠和设备中断处理
一.设备IRQ的suspend和resume 本小节主要解决这样一个问题:在系统休眠过程中,如何suspend设备中断(IRQ)?在从休眠中唤醒的过程中,如何resume设备IRQ? 一般而言,在系统 ...
- css常用标签及属性
css样式表常用的形式有三种,一.行内样式表.二.内部样式表.三.外部样式表 一. <p style="color:red;">nice to meet you< ...
- ansible 一些参数的整理
用ansible 来管理远程的主机,最大的好处是方便,ansible不用在远程的主机上安装ansible的客户端,ansible只要能通过ssh连接上远程主机就 能对它进行管理.也就是说ansible ...
- session和cookie的联系
前提: 一.cookie机制 正统的cookie分发是通过扩展HTTP协议来实现的,服务器通过在HTTP的响应头中加上一行特殊的指示以提示浏览器按照指示生成相应的cookie.然而纯粹的客户端脚本如J ...