Building RESTful Web Services in PHP7

Here is the book I have written recently on RESTful web services in PHP 7. The title is Building RESTful Web Services in PHP7 and is available on Amazon. You are probably wondering that why another PHP book. Why about RESTful web services. Many people consider RESTful web services as hitting a URI and getting JSON in response. However, this is a misconception. RESTful web service is more than that. And when it comes to Building RESTful web services then there  are numerous important things to consider.

Although there are already books on PHP and RESTful web services, this book is important because PHP and its ecosystem has evolved. “PHP7” in the title is to tell that we are talking about modern tools and ecosystem of PHP. Let me provide you detail of book in structured way. Let’s discuss different aspects of the book one by one.

Who is this book Useful for?

  • Anyone who have some basic PHP knowledge and want to build RESTful Web Service.
  • Developers who know basic PHP and have developed some basic dynamic website.
  • Developers who know basic PHP and have developed some basic dynamic website.
  • Developers who have learned PHP and worked mostly in Open source CMS like WordPress etc.
  • Developers who have used modern frameworks but not sure about critical pieces required to build RESTful API.
  • A seasoned PHP Developer, have created very basic API that returns data but want to make himself familiar with how it should be done according to REST standards and how it will work when authentication etc comes in and how to write tests for it.

What will Reader Learn?

  • REST API architecture and its benefits
  • How to write RESTful API web services in PHP7
  • To address security related issues in a REST API
  • Importance of automated testing and to write tests for API endpoints
  • Will be introduced to Micro-services architecture
  • Will understand security flaws in our API endpoints and tackle them effectively
  • The working of Lumen micro-framework and writing RESTful web services in it

Content of Book, Chapter by Chapter:

Chapter 1 RESTful web services, Introduction and Motivation:

This chapter is about introduction to Web Services, REST Architecture, RESTful Web Services, its comparison to other Web Services. HTTP Verbs, RESTful endpoints. It also explains RESTful web services concept by the use of Blog example and then talk about Response format and Response Code.

Chapter 2, PHP7, To Code It Better :

This chapter includes new features or changes on PHP7, which we will either use in this book or which are very important and worth discussing. As new features include features related to generators as well so introduced generators to user. Although generators were there already but rarely people use it. So this chapter also tells us about generators with examples.

Chapter 3, Creating RESTful Endpoints :

This chapter is about creating REST API endpoints for CRUD operations of a blog post in Vanilla PHP. Will also tell manual way of testing API endpoints through a REST client named as Postman.

Chapter 4, Reviewing Design Flaws and Security Threats :

In this chapter we will review what we have built in Chapter 3 and will highlight problems and flaws in it so that we can later improve that. It will include some security flaws as well. Some of the flaws and security threats in our application also fixed in this chapter while told about some of threats solution but not solved in this chapter but pointed towards open source package.

Chapter 5, Load and Resolve with Composer, an Evolutionary:

This chapter is about an evolutionary tool in PHP eco-system that is composer.This is not just an autoloader or package installer but a dependency manager. So one knows more about composer in this chapter.

Chapter 6, Illuminating RESTful Web Services with Lumen:

In this chapter we will introduce a micro-framework named Lumen. And will rewrite our RESTful web services endpoints in this micro-framework and will review how this tool will significantly improve our development speed as well as application structure.

In this chapter, users can first understand the Lumen framework, its components and then its usage to create RESTful web services’ endpoints.

Chapter 7, Improving RESTful web services:

This chapter will improve what is done in chapter 6 and we will learn and improve lot of stuff. User will create authentication, will make Transformer to separate how JSON structure should look like. Also user will improve web service in terms of security and will also learn about SSL.

Chapter 8, API Testing – Guards on the Gate:

This chapter introduces the need of Automated Tests. Will introduce different type of tests and then focus on API testing and teach user an automated testing framework named CodeCeption and will then write API tests in that testing framework.

Chapter 9, Microservices – An introduction

This chapter is about micro-services architecture. So we will understand and see benefits and challenges of Micro-services and will look into some of possible solutions or trade-offs. Introducing a new topic at the end of book normally doesn’t make sense. However, here this chapter point user towards Micro-services architecture that seems like the logical next step about how RESTful web services should be organized.


This is how I could present the content of the book. Feel free to let me know of your opinion. If you liked the book and want to buy then you can buy it from amazon:

Book Review: Full Stack Javascript by Azat Mardan

I got a book few months ago named “Full Stack JavaScript” by Azat Mardan, that I have read just now.  I also got a request for writing review of it. So here I want to share non-biased review which should be information for you guys to decide whether to read or not read this book.



Full Stack JavaScript is a book not about JavaScript as a language. If you are interested in JavaScript as a language, then either read or my previous article Good Resources For Learning Javascript . It is about how to use JavaScript when your role is Full Stack JavaScript developer. It don’t say it in book but this is what I got from it. It go through different tools and frameworks you need to know or approach that you should use. It give introduction to numerous things. Not only tools but also cloud platforms which you can use to deploy your app. It also discuss agile methodologies.

Content of Book:

In first chapter, Azat discusses Agile methodologies and frontend and backend concepts and flow and introduces NodeJS and MongoDB as well.

In second chapter, you can learn that how to setup your environment. Your local environment, setup Git for deployment, Windows Azure and Heroku deployment related stuff setup, your SSH Keys generation and MongoDB installation and setup.

Third Chapter name is JQuery and but it have lot of different things in it. Introduction to cross domain, AJAX and JSON. Then he introduced lot of stuff that is typically useful for frontend developers: JQuery functions, Twitter Bootstrap, LESS and then finally an example using Twitter API and JQuery. In same chapter, is used for an example app and then deployment on Windows Azure and Heroku. So in short he tried to cover all those different things implementation in one chapter.

Fourth chapter is mostly related to Backbone.js and its loading using AMD and require.js etc. Good thing about this chapter was that writer tried to cover only one thing in this whole chapter. Then in Chapter 5, it was related to usage of Backbone JS in example he started for Chapter 4 and 5 were better than previous chapters but unfortunately my intention wasn’t to learn backbone.js as I was more interested in Nodejs and MongoDB.

Chapter 6 and 7 were interesting for me as Chapter 6 is completely on Node JS and and Chapter 7 is completely on MongoDB.

In chapter 6, Azat explained NodeJS core modules and NPM and deployment on different could platforms. It was good to know NodeJS modules infromation but the key thing that he missed here was explainging Event Loop and flows. However, he showed usage with example, and introduced unit test for example code. Then instead of discussing how to test or what to test, he just provided a list of test frameworks.

Other interesting chapter is chaper 7 which is all about MongoDB. He told installation, configuration and usage of MongoDB.

Then in Chpater 8, writer just put everything together including examples of UI and API and deployment.

Pros and Cons and Opinion:

It is worth mentioning that everything discussed above in book is in no more that 208 pages. So it is good that you can get overview of all that stuff in 208 pages and it is bad because how much detail of so many things can be included in 208 pages? So it is good if you want to get overview of all that stuff in less time and in one book, but it is bad if you want to get detail of any of these things.

This book is more a list of articles introducing lot of different things and providing list of rest of stuff.

Writing Style:

Overall writing style of Azat Mardan is very good and code is well explained, however the way he structured chapters that is multiple things in one chapter, and one thing spanning over multiple chapters was little bit annoying.

So is this useful book for you?

It depends on who you are and what you want from this book. It is very good book for people who have JS language knowledge and aiming to be Full stack developer and want to immediately start learning different things Full Stack developer should know. But if you are like me, who already know about these things but want to get deeper look and wants to do development while taking occasionally opinion of writer, then it is not for you. Because this book gives overview of lot of stuff but does not get into depth of even one thing.

This is just my opinion after reading book, if you think anything different then feel free to discuss in comments below.

In case if you want to buy this book then you can buy it here: Full Stack JavaScript: Learn Backbone.js, Node.js and MongoDB

Good resources for learning Javascript

JavaScript is a widely used, amazing and misunderstood language by many developers. Its different concepts make it difficult for programmers coming from other languages. Here I am not going to explain different concepts but telling different resources learn JS (JavaScript).

Knowing basics of JS in browser (For Beginners):

If you are just a starter, who know some other language and want to quickly go through basics of Javascript, then quickest and basic way to do is to go through JS tutorials on W3Schools:

Understanding JS Beyond Basics:

Although W3Schools is good for beginning JS, however if you want to understand beyond basics, then there are couple of good books written on JavasScript. So here are two books I recommend for Learning Javascript:

Eloquent JavaScript:

Eloquent JavaScript is very recommended book for almost every one trying to learn JavaScript as a language not just a way to do some basic things in browser (W3Schools is already there for that purpose). It is very well written and suitable for most of people. Although it is easy to start with but it is not just basic, it also contains significant detail. This book is not just about language only but also covers different concepts for new comers. So even if you are new to programming, this book is awesome choice. Get it from Amazon.

If you are not intending to buy Paperback and interested in free online reading or PDF edition then get that from here:

Professional JavaScript for Web Developers:

This was the book from where I started understanding JavaScript. It is not just focused only on JavaScript as a language but also other things that you should know as a web developer. Also similar to Eloquent JavaScript, this book is easy to follow for beginners as well. Get it from Amazon.

Although I found these 2 books amazing for people who have basic JS knowledge but want to understand more, but there are many people who prefer videos instead of books, so in that case you can probably find something helpful on, however for developers with basic JS knowledge who want to improve, my recommendation goes with above mentioned books.

Advanced JavaScript:

By Advanced JavaScript, I mean something that experienced developers are interested in. Due to JavaScript’s different nature, many experienced developers face trouble understanding JavaScript in depth.

JavaScript Good Parts:

When it comes to understanding Javascript in depth, then there is an awesome book “JavaScript the Good Parts” written by Douglas Crockford

This book is sort of must read, if JavaScript is something that you are going to do seriously in future. You can get it from Amazon.

If you don’t like reading books, then good news is that on Frontend masters, there are courses by Douglas Crockford named as “JavaScript the Good Parts” and “The Good Parts of JavaScript and the Web”, so you can watch them there as well, however I personally don’t think that whole book can be gathered in those video courses.

Advanced JavaScript by Kyle Simpson:

Another awesome advanced level video training course on Javascript is Advanced JavaScript by Kyle Simpson, available on as well as on

Next JavaScript books in my Wishlist:

This is not where it stops, if you want to know more about which JavaScript books are next in my wishlist, then you can check them here on amazon:

Free JavaScript Ebooks:

If you don’t want to buy anything and only looking for online or free PDF resources, then you can get many free JavaScript ebooks here:


Good friends don’t forget to share good resources with their friends, so share it with your friends as well.

Fix Uncaught ReflectionException: Class log does not exist …/laravel/framework/…

I again got this error which left me no clue of what happened wrong and how can I fix it.

PHP Fatal error: Uncaught ReflectionException: Class log does not exist in .../vendo/laravel/framework/src/Illuminate/Container/Container.php:741

I tried to find solution on google for a while and came to know that this don’t tell what acually went wrong. There can be different things which can be in different case. And you will find nothing other than someone will be telling that this error just mean something crashed earlier on before that interface was bound. So it tells nothing useful.

I found different reasons for this, but most commonly it was after you updated something in your system, which effected some extension of php or something else went wrong.

Here I am not going to dig deeper into why it happened because there can be lot of different reasons, I am just trying to tell a way by which I came to know the reason and fixed it. It happened to me twice in last few months and I found nothing on stackoverflow so that’s why I am writing it here.

So here are steps to find the reason and fix:

  1. Good thing about Laravel is that it checks some obvious dependencies which are required for Laravel to function properly. So go to some other directory and try installing Laravel’s same version there.  You can install it using
    composer create-project --prefer-dist laravel/laravel blog

    while in my case I was using Laravel bootstrap so I ran

    composer create-project graham-campbell/bootstrap-cms --prefer-dist -s dev
  2. It will show you missing dependencis, so you can see the dependencies and try to resolve them by installing missing extensions. In my case it was ext-mbstring  missing and in someone else’s case it was php-mysql extension missing. So install whatever extension is missing in your case.
  3. After installing extension don’t forget to restart apache:
    sudo service apache2 restart
  4. Once you have those extensions installed and your able to complete Laravel installation, go back to actual Laravel installation directory where you were actually facing above mentioned issue.
  5. Once you are there, give all permissions to `storage` and `bootstrap/cache` directories in Laravel installation by doing:
    sudo chmod 777 storage -R
    sudo chmod 777 bootstrap/cache -R
  6.  Now execute following command:
    php artisan clear-compiled
  7. If you see error like:
    PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in ...dynamic/bootstrap/cache/compiled.php on line 737
    Script php artisan clear-compiled handling the post-install-cmd event returned with an error[RuntimeException]Error Output: PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in /var/www/html.../bootstrap/cache/comp

    Delete the contents of the bootstrap/cache folder, then run

    php artisan app:update 

    and try running

     php artisan clear-compiled


  8. After doing so just run:
    composer dump-autoload
  9. And then go to your browser and try to reload. Most probably it should be working as this is how I had it working twice.

In case it still don’t work, then post it in comment and we can try to dig into that.

How to setup Atom for PHP Development

What is Atom and why it is awesome?

Atom is a hackable text editor. I normally don’t like the idea of text editors which need settings and different plug-ins installations to be some what equivalent to a complete IDE but after using Atom with some configurations and plug-in installation, my opinion is changed.

What now I think is that a hackable editor is actually good because it provide you option to only have functionality what you exactly need while still being very light-weight.

Using Atom as PHP IDE:

I came to Atom from Netbeans, when it became very slow and made overall system very slow. I never liked Netbeans’ non-smooth fonts on Ubuntu but didn’t find any good option. But after slowness issue, I tried Atom as text editor and then found it much more powerful by utilizing packages available. So now I use it for PHP development with useful features without making my system slow.

Please note that these packages will not make it equivalent to a premium tool like “PHP Storm”( in fact never compare other IDEs with JetBrains’ IDEs unless you don’t want to pay 100$+ for IDE. ), but still Atom with packages will be better experience in many ways as compared to other editors and IDEs. If you are currently using some text editor like notepad++ or brackets, or tools like Aptana or Eclipse, you will like Atom with these packages. And obviously your system will feel much better if you are coming from Netbeans.

Installing Atom:

Simply go to and download the build for your release and then simply install it. It don’t have any hard dependency like Netbeans need JRE. By just installing Atom, you can start using it as a simple text editor with smoother fonts and awesome themes.

Atom for JS:

Most of PHP developers also need to interact with JS and front-end. So you will want JS support as well. Atom come with some JS related packages already installed with Atom.

Atom Settings and packages:

To see atom packages, themes and other configurations then go to:

Top menu > Packages > Settings View > Open


simply press ctrl + , (control and comma key)

You should see this settings screen:

Now scroll down and find field labeled as Tab Length” and change its value to 4 instead of 2 as per PSR2 standard. ( )

Atom Packages:

In atom, you need to install packages to extend Atom and have more feature set. Here are some important packages listed below with their detail. Please note that Atom package can be installed using settings window as well as this command:

$ apm install <package-name>

PHP CS Fixer:


PHP CS fixer runs the “PHP Coding Standards Fixer” within your Atom Editor. Install this package but it will not start functioning. This package requires the “PHP Coding Standards Fixer” Cli build by SensioLabs wich can be installed using composer:

$ ./composer.phar global require fabpot/php-cs-fixer

Above package is abandoned so this one can be used:

$ ./composer.phar global require friendsofphp/php-cs-fixer

then go to settings provide path to php-cs-fixer and PHP. Also click on “Execute on Save” check box so that on save, it will format it according to psr2 standards.

Linter PHP:

linter-php error screen
linter-php error screen

Install this package so that your Atom know in case of any PHP syntax error  you make. It will show you proper error within your editor. This is very important unless you used to write PHP in conventional text editor.

It will work without any further settings if your php is accessible globally through command line. Otherwise you will need to provide PHP executable path in this package’s settings.

PHP Hyperclick:

Hyperclick provider for PHP. Open file when classname is clicked. This is simple and very useful package but installing it alone will not work. So you will also need to install dependency  that is Hyper Click (another package of Atom).

In case if it don’t work with “ctrl+click ” then try “alt+ctrl+click” .

Last words:

These are just few packages that I have installed and made my Atom editor  better, at least I no more miss Netbeans (which I was using for last ) for doing some work in modern framework like Laravel. But I expect a lot of more awesome surprising packages other than these. So keep exploring and let me know about your favorite atom packages in comment.


Installing MongoDB Driver (with MongoDB extension) on Ubuntu and other Linux distro.

Previously “Mongo” was the extension used for MongoDB (Legacy) driver for PHP. Now that is depreciated. Now “MongoDB” Pecl extension is used instead of  “Mongo” Pecl extension. And MongoDB Driver is PHP’s official driver for MongoDB. Here is detail of this driver on . It supports PHP as well as HHVM.

To have this MongoDB driver working, you need to install pecl “MongoDB” extension.

To install PHP MongoDB on Linux, follow below mentioned steps:

  1. Run this command:
    sudo pecl install mongodb
  2. Then add following line to php.ini
  3. Then you need to restart your apache or nginx . If you are using apache then use following command to reload it.
  1. service apache2 reload

    To test your installation try instantiating “MongoDB\Driver\Client” by using code similar to this one:

    $client = new MongoDB\Driver\Client("mongodb://localhost:27017");

    If it says that MongoDB\Driver\Client not found or not defined then there is chance that MongoDB driver is not properly installed. However parameters to this constructor can be changed depends on your MongoDB URL.

    In case of any problem, feel free to let me know in comments section.

Fundamentals of D3 visualisations

D3.js is a popular SVG based data visualization library and there are many reasons for its popularity. D3.js provides foundations and components for creating data visualizations instead of providing some already built charts. Another big reason of D3.js popularity is that it don’t use a new technology but rely on existing web standards.

  1. HTML
  2. CSS
  3. DOM
  4. SVG

Probably some of you have heard about SVG but don’t know what exactly it is. SVG stands for Scalable Vector Graphics. If you guys haven’t much time and want to know very basic of SVG then see . If you are one of those guys who want to study in detail then this book named SVG Essentials seems promising.

There are 3 things at which D3.js is very good.

  1. Data manipulation and calculations
  2. DOM manipulation
  3. SVG creation and manipulation

In fact D3 magic depends on these 3 things together. D3 embeds Data in DOM after manipulation and parsing it in different ways and use SVG where graphics is required.

Data Manipulation and Calculations:

D3 stands for Data Driven Documents. So first D in D3 stands for Data.  And D3 provides different ways for manipulating data and doing different calculations. For example, D3 provide different array related methods as shown here: .

Other than arrays D3 also have variety of methods to work with time and time intervals, detail can be found here:

DOM Manipulation:

It is easy to Manipulate and Bind data with DOM. A simple bar chart code can be seen here as well:

/* set the CSS */
body { font: 12px Arial;}
.bar {
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
border:solid 1px #fff;
function getDataValue(d) {
	var barHeight = d * 5;
	return barHeight + "px";
        .append('div').attr('class', 'bar').style('height', getDataValue);


Here we only utilized D3’s interaction capabilities with DOM instead of using any SVG related feature. While SVG is much more feature rich when it comes to visualizations.

SVG Creation and Manipulation :

D3 can utilize HTML DOM elements to visualization as well but actual format used for visualization by D3 is SVG. It is because SVG provide a lot more variety of graphical features than an HTML DOM. A very basic thing you can do in D3 is to draw and SVG line. But this is not the limit, you can create shapes, polygons and different gradients etc. In fact you can do whatever you can do in other vector graphics tool like Adobe Illustrator and Inkscape.  Also D3 can provide very good animation related functionality as well.

Data Visualization Steps using D3.js

There are 3 major steps.

  1. Have data parsed and formatted based on how you need it to draw its visuals.
  2. Bind an SVG element in DOM.
  3. Draw whatever you want in SVG element.

There can be more steps if you want behavior, animation and user interaction however above mentioned steps are major steps.

Recommended Book

Although there are many books on D3.js. But if you want to learn it in detail then this book: Interactive Data Visualizations for the Web by Scott Murray can be very helpful. However, I will talk more about D3 its learning resources in next posts so if you don’t have time for book, you can still know more learn D3.js. But keep in mind that blog is no replacement of such awesome book.

Should I use D3 for creating charts and graphs?

What is D3 ?

D3.js is an open source Javascript library intended for data visualization purpose. “D3” stands for Data Driven Documents. It can also be used for creating and manipulating SVG files.  And different charts or graphs can also be plotted using D3 easily.

How D3 is different?

D3 is not similar to other charting solutions like Fusion charts and high charts etc. It don’t just take JSON and render a graph based on some predefined options but D3 let you plot the whole graph. It is comparatively low level library where developer plot the graph and create all graph elements and define its behavior. Although that is more time consuming but that also provide complete control in developer’s hand so it is very flexible. You render each and every element how you want it.

In  case of other charting solutions you choose which type of chart you want to plot and some other configurable options and call the function which renders graph/chart. That type of graph rendered and that’s all. Then it all depends on charting solution that what it returns. Some returns canvas based result while some renders an SVG.

When to Use D3 ?

A common understanding is that D3 should be only used if you are going to draw a graph which nobody has ever built. This is wrong. This can be the one reason but it is not the only one. If you simply want to customize the charts and want to look and work it exactly like some design, then D3 is something you can use. At  the same time one need to understand that it is something that will consume more time.

Another reason can  be to use D3 when you want every day graphs but you want them to  be look much different and behave different than what other frameworks are providing. If you want some extra elements that no charting solution is providing then D3 can be an option. As D3 is something which let you actually plot graphs and manipulate SVG elements through basic building blocks so by using those building blocks, you can create your own graphs with lot of flexibility.

D3 is very much useful when at time of starting building graph, your requirements are open ended and your clients don’t want to compromise on what they want. Other libraries graphs can have limits because they are already plotted with fix number of options so they will be rendered accordinlgy, while in D3 every element is placed by developer as he want it.

Why not customize other Charting solutions?

Many managers or people concern about deadlines often ask this question. Obviously time-line is important. No solution is good solution if it can’t be provided on time. First of all customizations can be of two types: Appearance and behavior.

Appearance can be customized through CSS if SVG is rendered by charting library.  But in case of chart’s or graph’s behavior, options are limited. There are many options which can be passed in JSON at time of initialization but still a chart or graph can render what it have. If you simply don’t have some option like if you want crosshair values to appear separately and your charting library provide it along with crosshair line then you normally cant change that.

So in short it can’t provide that level of flexibility that D3 can. So in case you have tight deadline and open ended requirements then you need to choose smartly between those two things.

What about D3 based charing libraries?

There are charting libraries which are based on D3. One example is C3.js . C3 is based on D3 and have cleaner API as well but it still don’t provide as much flexibility as D3 can. However, if you find limitations in C3 solution you can start using D3 there as well. But problem is that once you are using C3 and getting SVG, then to customize via d3 you need to manipulate that SVG directly and direct SVG manipulation is very low level thing. So that can even consume more time because in D3 you don’t always need to draw every SVG element but to customize a rendered SVG you may need to manipulate every single item.

So for flexibility should you never use D3 based charting libraries?

Actually you can use them but if you want more flexibility then either use D3 directly or use that D3 based charting library which provide you access to D3 components directly.

For example if that library make D3 axis and scale function and generate graph based on that, then it is better if you can access those same scale and axis function to use with D3. So that you can render them or change them if you want instead of using D3 to just change SVG elements of rendered graph.

Are there good resources for learning D3?

Actually D3 has a detailed documentation which is I think enough to understand D3. Also there are many D3 examples available as well as some books are written on D3 which can provide understanding of D3 to start.  There are also some video trainings available but I think those are mainly on data visualizations rather than on D3.

Is D3 easy to learn?

Actually with D3 documentation, I think it is easy to learn but you need to have a good mathematical mind. At-least a mind which don’t mind doing some calculations because many times you will be telling it where to render what. After all, great power come with great responsibility.


Configuring and using Laravel with 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:

MongoDB installation:

If you haven’t already installed MongoDB then MongoDB have separate guides for installing it own different Operating Systems. So check that:

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:

To install MongoDB driver on ubuntu  or other Linux distributions, follow steps mentioned here:

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.


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:


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:


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 :


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:

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 .

Installing MongoDB driver for PHP on Ubuntu and other Linux distributions

Mongo is official MongoDB driver for PHP. Here is detail of this driver on . Mongo include MongoClient class which is required to connect MongoDB and required by several packages that bridge between MongoDB and PHP.

MongoClient works on almost all of Operating Systems including Windows, Mac OS X, Unix, and Linux; little- and big-endian machines. No matter 32 or 64-bit machines. PHP 5.3 through 5.6. To install it, there is a “mongo” package on PECL.

To install PHP Mongo on Linux, follow below mentioned steps:

  1. Run this command:
    sudo pecl install mongo
  2. If response of above command is error with text “phpize not found” then you need to first run this command and then above one. Please note that this command is useful on Debian based distributions, for others please use appopiate command accordingly :
    sudo apt-get install php5-dev
  3. Then add following line to php.ini
  4. Then you need to restart your apache or nginx . If you are using apache then use following command to reload it.
  5. service apache2 reload

    After this hopefully your PHPClient class will be working fine and you can test your code which use MongoClient class.

    In case of any problem, feel free to let me know in comments section.