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 安装成功后,通过如下 ...
随机推荐
- 关于android屏幕适配的问题(drawable-xxxxxxxx,dp,sp,px等等),偶尔看到了android源代码,关于dpi的区分的值
上一篇博客说了一下.9.png图片http://blog.csdn.net/qq_23195583/article/details/46737419 当然,点九的是指的能够进行拉伸的.那么假设图片不能 ...
- JSON与Bean互转
转自: 关于json与javaBean之间的转换 废话不多说,直接进入主题,json与javaBean之间的互相转换 javaBean转换成json 直接使用提供的方法可以得到json JSONObj ...
- struts2 中请求转发与请求重定向方法
本文转自:http://blog.csdn.net/a327736051/article/details/50240491 一.Chain Result:这个result调用另外的一个action,连 ...
- Lucene的索引不跨平台
在windows上使用Lucene生成索引文件,将索引文件复制到Linux服务器上,报错"校验错误,可能是硬件问题". 所以,Lucene的跨平台只是代码跨平台,生成的索引不跨平台 ...
- 使用Block在两个界面之间传值
首先,创建两个视图控制器,在第一个视图控制器中创建一个UILabel和一个UIButton,其中UILabel是为了显示第二个视图控制器传过来的字符串,UIButton是为了push到第二个界面. 第 ...
- eclipse修改文件编码
http://topic.csdn.net/u/20080724/14/428de399-790d-442a-8340-3a5fb6dcfcee.html[修改文件编码,假设JS] 在Eclips ...
- 分布式缓存技术memcached学习系列(五)—— memcached java客户端的使用
Memcached的客户端简介 我们已经知道,memcached是一套分布式的缓存系统,memcached的服务端只是缓存数据的地方,并不能实现分布式,而memcached的客户端才是实现分布式的地方 ...
- iOS 即时通讯,从入门到 “放弃”?
原文链接:http://www.jianshu.com/p/2dbb360886a8 本文会用实例的方式,将 iOS 各种 IM 的方案都简单的实现一遍.并且提供一些选型.实现细节以及优化的建议. — ...
- R.string获取的是数字或者R.integer数字不对的问题
String msg = R.string.menu_title; 获取menu_title的String值,但发现这样写报错,原因R.string.menu_title是int类型的,可是通过以下方 ...
- Dynamic DMA mapping Guide
一.前言 这是一篇指导驱动工程师如何使用DMA API的文档,为了方便理解,文档中给出了伪代码的例程.另外一篇文档dma-api.txt给出了相关API的简明描述,有兴趣也可以看看那一篇,这两份文档在 ...