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 安装成功后,通过如下 ...
随机推荐
- 题目:vbs批量开通工具,实现vbs开通的ux设计和流程调度
题目:vbs批量开通工具,实现vbs开通的ux设计和流程调度 需求点:支持开通前检查(检查失败不允许开站),开通过程监控,开通后业务检验,失败后重新开通,支持部分站点开通(比如用户导入的模板中有10个 ...
- 什么是RESTfull?理解RESTfull架构【转】
越来越多的人开始意识到,网站即软件,而且是一种新型的软件. 这种"互联网软件"采用客户端/服务器模式,建立在分布式体系上,通过互联网通信,具有高延时(high latency).高 ...
- epoll 系列函数简介、与select、poll 的区别
一.epoll 系列函数简介 #include <sys/epoll.h> int epoll_create(int size); int epoll_create1(int flags) ...
- Unix环境高级编程(一)文件I/O
Unix系统中大多数文件I/O只需用到五个函数:open.read.write.lseek.close.本章说介绍的I/O是不带缓冲的,即:每个read和write都调用内核中的一个系统调用.不是IS ...
- kubernetes 二
部署harbor Habor是由VMWare中国团队开源的容器镜像仓库.事实上,Habor是在Docker Registry上进行了相应的企业级扩展,从而获 得了更加广泛的应用,这些新的企业级特性包括 ...
- tomcat6的编译和导入myeclipse
声明:近期在学习tomcat6的源代码,网上搜索了些相关的资料,并自己操作了下进行了对应的汇总.如今总结例如以下 本文目的:编译tomcat6源代码+导入tomcat6源代码到myeclipse 測试 ...
- 基于Unity3d 引擎的Android游戏优化
原文地址:http://blog.csdn.net/jixuguo/article/details/9018669 近期项目进入收尾阶段,之前对项目做了非常多优化,mesh合并 .降低DrawCall ...
- Codeforces 86C Genetic engineering (AC自己主动机+dp)
题目大意: 要求构造一个串,使得这个串是由所给的串相连接构成,连接能够有重叠的部分. 思路分析: 首先用所给的串建立自己主动机,每一个单词节点记录当前节点可以达到的最长后缀. 開始的时候想的是dp[i ...
- man-pages项目包含文档的说明
man-pages项目是由linux kernel维护的一个文档项目,但是,该项目中只是包含了部分常用文档,还有大量gnu常用系统工具的manpanges没有包含,但一些在线网站提供一个详细版本的ma ...
- 【Android】12.3 在当前Activity中获取另一个Activity的返回值
分类:C#.Android.VS2015: 创建日期:2016-02-23 一.简介 在上一节的示例中,通过StartActivity(Intent)方法启动另一个Activity后,这两个Activ ...