Monday, 31 October 2016

Google Golang for Beginners

Computer programming is the art, craft and science of writing programs which define how computers operate.So in this post i will show you how to start programming with Golang (by google).Go is a general purpose programming language with advanced features and a clean syntax. Because of its wide availability on a variety of platforms, its robust well documented common library, and its focus on good software engineering principles, Go is an ideal language to learn as your first programming language.

Go lang :

Features of language Go :

Interfaces to replace virtual inheritance.
Syntax and environment adopting patterns.
Compiled into statically linked native binaries without external dependencies.
Remote package management.
Online package documentation.
Built-in concurrency primitives.
Large built-in library.
Type embedding to replace non-virtual inheritance.
Simple language specifications.
Fast compilation time.
Light testing framework.

How to install go lang in ubuntu : 

Step 1 : Open your terminal

curl -O

Next, you can use sha256sum to verify the tarball:

sha256sum go1.6.linux-amd64.tar.gz

Step 2 : Extract the tar.

tar xvf go1.6.linux-amd64.tar.gz

Step 3 : Permission change for go.

sudo chown -R root:root ./go
sudo mv go /usr/local

Step 4 : Set Go's root value which tells go where to look for its files.

sudo nano ~/.profile

Add these lines at the end of file

export GOPATH=$HOME/work
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin

After save the file close the file and refresh your profile by using command .

source ~/.profile

Step 5 : Create a simple hello program for go.

nano ~/work/src/hello.go

import the package for go 

package main

import "fmt"

func main() {
    fmt.Printf("hello world for go\n")

Save and close the file then compile it by invoking the Go command install:

go install ~/work/src/hello

With the file compiled you can run it by simply executing the command:


if this will return hello world for go , that means successfully installed the lang go. This is just the begining steps to install go lang . I hope you enjoy the post please share and comment.

Saturday, 29 October 2016

Awesome date functions PHP

Dates are always an important part of any website but sometime it's very difficult to deal with, especially for beginners. So here is a list of a few some important php functions and code snippets that will definitely help you dealing with dates.

Php Date

Get Current time :
It's basic function takes no parameters and returns the current date. This example uses British date formatting, you can change it on line 2.

function nowDateInUk(){
 return date('d/m/Y', time());

Format A Date :
The simple way to convert a date from a format (yyyy-mm-dd) to another.For more extensive conversions, you should have a look at the DateTime class to parse & format.

$originalDateNow = "2016-10-29";
$newDateNow = date("d-m-Y", strtotime($originalDateNow));

Convert minutes to hours and minutes :
This is a super useful function for displaying times. Give it minutes as an integer (let's say 135) and the function will return 02:15.

function cnvToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);

Get A week Number from date :
Sometime you need to find the week number of a particular date. Pass your date as a parameter to this function, and it will return you the week number.

function findWeekNumber($ndate){
 $res = new DateTime($ndate);
 return $res->format("W");

Difference between two dates:
This function takes two dates and returns the interval between two dates. The result is set to be displayed in hours and minutes.

function getDateDiff($date1, $date2){
     $datetime1 = new DateTime($date1);
 $datetime2 = new DateTime($date2);
 $interval = $datetime1->diff($datetime2);
 return $interval->format('%H:%I');

Check date is past or future :
Sometime you need to check that date which you are using is past date and future. So these functions will help you.

if(strtotime($dateString) > time()) {
     # your date is in the future

if(strtotime($dateString) < time()) {
     # your date is in the past

if(strtotime($dateString) == time()) {
     # your date is right now

Calculate age from date :
Very useful on websites where you need to check that a person is over a certain age to create an account.

function getAge($date){
    $time = strtotime($date);
    if($time === false){
      return '';
    $year_diff = '';
    $date = date('Y-m-d', $time);
    list($year,$month,$day) = explode('-',$date);
    $year_diff = date('Y') - $year;
    $month_diff = date('m') - $month;
    $day_diff = date('d') - $day;
    if ($day_diff < 0 || $month_diff < 0) $year_diff-;
    return $year_diff;

I hope you like the post . If you like please share.

Wednesday, 26 October 2016

Some time saving commands of vim

Vim is an advanced text editor that seeks to provide the power of the de-facto Unix editor 'Vi', with a more complete feature set.  Since the 1970’s, Vi and Vim are popular amongst developers and are present on most UNIX-based servers.

Vim Editor

I'm showing you some good shorthand codes of vim it will charge your coding speed.

Some Basics Vim:

:e filename Open filename for edition
:w Save file
:q Exit Vim
:q! Quit without saving
:x Write file (if changes has been made) and exit
:sav filename Saves file as filename
. Repeats the last change made in normal mode
5. Repeats 5 times the last change made in normal mode

Some Moving file operations:

k or Up Arrow move the cursor up one line
j or Down Arrow move the cursor down one line
e move the cursor to the end of the word
b move the cursor to the begining of the word
0 move the cursor to the begining of the line
G move the cursor to the end of the file
gg move the cursor to the begining of the file
L move the cursor to the bottom of the screen
:59 move cursor to line 59. Replace 59 by the desired line number.
20| move cursor to column 20.
% Move cursor to matching parenthesis
[[ Jump to function start
[{ Jump to block start

Some Cut Copy Commands:

dd Cut current line
yw Yank word
y Copy the selected text to clipboard
yy Copy current line
y$ Copy to end of line
p Paste clipboard contents
D Cut to end of line

Some Search cheat sheet:

/word Search word from top to bottom
?word Search word from bottom to top
* Search the word under cursor
/\< ¦.\> Search all words of 4 letters
/\cstring Search STRING or string, case insensitive
/jo[ha]n Search john or joan
/\< the Search the, theatre or then
/\< the\> Search the
/\<\d\d\d\d\> Search exactly 4 digits
/^\n\{3} Find 3 empty lines
/the\> Search the or breathe
/\/ Search fred but not alfred or frederick
/fred\|joe Search fred or joe
:bufdo /searchstr/ Search in all open files
bufdo %s/something/somethingelse/g Search something in all the open buffers and replace it with somethingelse

Replace Commands :

:%s/old/new/g Replace all occurences of old by new in file
:%s/onward/forward/gi Replace onward by forward, case unsensitive
:%s/old/new/gc Replace all occurences with confirmation
:%s/onward/forward/gi Replace onward by forward, case unsensitive
:%s/ *$//g Delete all white spaces
:2,35s/old/new/g Replace all occurences between lines 2 and 35
:5,$s/old/new/g Replace all occurences from line 5 to EOF
:%s/^/hello/g Replace the begining of each line by hello
:%s/$/Harry/g Replace the end of each line by Harry
:%s/\r/\r/g Transform DOS carriage returns in returns
:%s#<[^>]\+>##g Delete HTML tags but keeps text
:g/string/d Delete all lines containing string
:v/string/d Delete all lines containing which didn’t contain string
:s/Bill/Steve/ Replace the first occurence of Bill by Steve in current line
:s/Bill/Steve/g Replace Bill by Steve in current line
:%s/^\(.*\)\n\1$/\1/ Delete lines which appears twice
Ctrl+a Increment number under the cursor
:%s/Bill/Steve/g Replace Bill by Steve in all the file
:%s/^M//g Delete DOS carriage returns (^M)
Ctrl+x Decrement number under cursor
ggVGg? Change text to Rot13

Read Write cheat:

:r infile Insert the content of infile
:1,10 w outfile Saves lines 1 to 10 in outfile
:1,10 w >> outfile Appends lines 1 to 10 to outfile
:23r infile Insert the content of infile under line 23

Explorer file:

:browse e Graphical file explorer
:ls List buffers
:e . Open integrated file explorer
:cd .. Move to parent directory
:args List files
:Sex Split window and open integrated file explorer
:Sex! Same as :Sex but split window vertically
:args *.php Open file list
:grep expression *.php Returns a list of .php files contening expression
gf Open file name under cursor

Syntax highlighting :

:syntax off Turn off syntax highlighting
:syntax on Turn on syntax highlighting
:set syntax=perl Force syntax highlighting

I hope you like the post please share and comment.

Monday, 24 October 2016

Create your first widget in Yii2

In this tutorial i will show you how you can create own custom widget in Yii2.The main advantage of Widget is you can write once and reuse it wherever you need it in your view. Widgets are reusable blocks and they are used in your views. Create a custom widget we must extend the base widget yii\base\Widget and we have to override the init() or run() methods of base widget.

Yii2 Widget

Step 1: Create a folder named components or changed name in your project folder.

Step 2: Create a file with desired widget name inside components folder and paste the below code. Example – HelloWidget.php


namespace app\components;

use yii\base\Widget;
use yii\helpers\Html;

class Hellowidget extends Widget

    public $msg;

    public function init()

        if ($this->msg === null) {
            $this->msg = 'Welcome Here';
        } else {
            $this->msg = 'Welcome ' . $this->msg;

    public function run()
        // you can load & return the view or you can return the output variable
        return $this->render('my-widge', ['message' => $this->msg]);

In HelloWidget is a class and we can access the widget like 'app\components\HelloWidget'.

Step 3: Create a view and put the content into it.

Step 4: Everything is can call now widget.

<?php echo \app\components\HelloWidget::widget() ?>

I hope you like the post. please share and comment.

Saturday, 15 October 2016

How to create a webpage screenshot with NodeJs and PhantomJS

To create webpage screenshots we are using PhantomJs. PhantomJS is a headless WebKit scriptable with a JavaScript API. It has very fast and native support for various web standards like DOM handling, CSS selector, JSON, Canvas, and SVG. In simple words PhantomJS is a web browser without a graphical user interface.Assuming you already downloaded and installed PhatomJS, create a JavaScript file (capturescreen.js) with the following contents.


var wpage = require('webpage').create();'', function() {

Then you need to run this script in browser it won't work. you need to run in command line.

phantomjs capturescreen.js

After running this see in the same folder a png file is create of screenshot.For more option you can read the phantomJs here.Please feel free to comment below for suggestions and problems.

How to serve static files with node.js

In front end development to serve static files such as images, CSS files, and JavaScript files you require the web servers. and you need a server like apache or nginx servers to server files.Installing http server and configuration is much hactic for a frontend developers.With the help of node.js we can easily create a http web server.if you are using node.js environment then there is quick configuration package for HTTP server without writing a single line of code.


Assuming you have Node.js installed in your machine.If node.js not installed please read this article Getting started with node.js. You need to install the module called http-server using the following command.

npm install -g http-server

That’s it. Now you can serve any static files and assets using this module. Now you switch to any folder and run the server using the following command and your folder will act as server and it will serve static files such as images, CSS files, and JavaScript files.

~/Desktop mkdir assets && cd $_
~/Desktop/assets http-server

Now assets folder will act like root of the Http server.Please feel free to comment below for suggestions and problems.

Pagination in laravel 5

Laravel provides pagination for Eloquent results which comes out of the box features but for custom data set we need to create paging.i'm using laravel5 LengthAwarePaginator class to show you how to create a pagination from a array of data.

Laravel Pagination

Step 1: Controller – app/Http/Controller/RecordsController.php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests;

class RecordsController extends Controller

    public function items(Request $request)
        $items = [

        // Get current page form url e.x. &page=1
        $currentPage = LengthAwarePaginator::resolveCurrentPage();

        // Create a new Laravel collection from the array data
        $itemCollection = collect($items);

        // Define how many items we want to be visible in each page
        $perPage = 1;

        // Slice the collection to get the items to display in current page
        $currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();

        // Create our paginator and pass it to the view
        $paginatedItems = new LengthAwarePaginator($currentPageItems, count($itemCollection), $perPage);

        // set url path for generted links

        return view('records_view', ['records' => $paginatedItems]);

Step 2: View (resources/views/records_view.blade.php) file should look like this.

<h1>Records List</h1>
@foreach ($records as $record) 
   <li> {{ $record }} </li>
{{ $records->links() }}

Step 3: Now comes to the routing app/Http/Routes.php.


Please feel free to comment below for suggestions and problems.

Api routing in slim framework 3

Slim framework router component allows to define routes that are mapped to callback handlers which receive the request. The Slim Framework’s router is built on top of the nikic/fastroute component, and it is remarkably fast and stable. A router simply parses a URI to determine the request and gives appropriate response to it.If you are new to slim framework then read this post also getting started with slim.

Slim framework

Slim get request: 

require __DIR__ . '/../vendor/autoload.php';
$appObj = new \Slim\App();
$appObj->get('/', function($request, $response) {
      $response->write("welcome to slim");
      return $response;

The Slim Framework provides methods for the most popular HTTP methods.

$appObj->get() - It handles only GET HTTP requests 
$appObj->post() - It handles only POST HTTP requests 
$appObj->put() - It handles only PUT HTTP requests 
$appObj->patch() - It handles only PATCH HTTP requests 
$appObj->delete() - It handles only DELETE HTTP requests 
$appObj->options() - It handles only OPTIONS HTTP requests 
$appObj->map(['get', 'post']) 

How to define Dynamic routes in slim:

   function($request, $response, $args) {
           $name = $args['name'];
           return $response->write("Hello $name");

How to maintain Regex in Routes in slim:

$appObj->get('/user/{id:\d+}', $callable);
     $appObj->get('/hello/{name:[\w]+}', $callable);
     $appObj->get('/hello{a:/{0,1}}{name:[\w]*}', $callable);
     <h3>Route groups</h3>
     $appObj->group('/books', function () use ($app) {
     $appObj->get('', function ($req, $res) {
            // Return list of records
     $appObj->post('', function ($req, $res) {
            // Create a new record
     $appObj->get('/{id:\d+}', function ($req, $res, $args) {
           // Return a single record
     $appObj->put('/{id:\d+}', function ($req, $res, $args) {
            // Update a record

How to maintain Named routes in slim:

// Name the route
$appObj->get('/hello/{name}', function(...) {...})
// build link:
$link = $appObj->router->urlFor('hi', ['name' => 'John']);
creates: /hello/John

Please feel free to comment below for suggestions and problems.

Getting started with slim framework 3 of PHP

Slim is a micro framework that helps you create a simple web applications and api's. It comes with the middleware architecture and url dispatcher that makes it ideal for static websites or API prototyping. It supports all(GET, POST, PUT, DELETE) the HTTP methods. It requires PHP 5.5.0 or newer.

Slim framework

In this article i will show you how to install Slim Framework. It is extremely easy to setup, thanks to composer support.

Step 1: Installation 

# go to your projects directory
$ cd var/www/html
# create new project directory 
$ mkdir myslimapp
#change into the App directory
$ cd myslimapp
# install slim via composer
$ composer require slim/slim "^3.0"

Above issued composer command will install Slim and all required dependencies.Now create a index.php to say hello.

Step 2: Create a action which print hello.

require 'vendor/autoload.php';
$app = new Slim\App();
$app->get('/hello/{name}', function ($request, $response, $args) {
    $response->write("Hello Slim , " . $args['name']);
    return $response;

Step 3: Go to browser and type  http://localhost/myslimapp/hello/john
without .htaccess

If you want to remove index.php from the URL, then change the apache configurations with .htaccess. The .htaccess file should look like this.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Check the permission for index.php and .htaccess.Please feel free to comment below your suggestion and problems..

Sunday, 9 October 2016

Contribute to opensource Hacktoberfest.

Opensouce : It means a software which is available to everyone for inspect, modify and enhance.The software being distributed must be redistributed to anyone else without any restriction.Open source applications are generally freely available although there’s nothing stopping the developer from charging for copies of the software if they allow redistribution of the application and its source code afterwards.

Hacktoberfest 2016

If you are opensource lover than Hacktoberfest is for you. Celebrate open source this October by participating in Hacktoberfest, a month long festival of code organized by DigitalOcean and hosted on GitHub.

How to participate in hacktoberfest : You can choose any project from the list of opensource hosted in GitHub and contribute by sending a pull request.You can just simply solve a bug add new feature or even improve the documentation of the project.Once you made your contribution sharing with other #hacktoberfest (hashtag).you can check out the guide of how to contribute to opensource.

Get your cool t-shirt after making a four pool request to any opensource project.
  • Sign up on the Hacktoberfest website.
  • Four pull request atleast on any github hosted project by 31st October 2015.
  • At the end of this month DigitalOcean will collect your shipping details and mail your shirt.

You can read more information here : DigitalOcean

Saturday, 8 October 2016

How to use DB Facade for query in laravel

Facades : It provide a "static" interface to classes that are available in the application's service container.The facades serve as "static proxies" to underlying classes in the service container , providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

Laravel raw query

In this post i will show you how to use DB facade for db operations. In sometime you need to use direct query without using model class. So you can use the direct DB facade for all the insert, update,select operation in database.

You can use it by adding a namespace.

use DB;


$result = \DB::table('tablename')->get();//You have to tell PHP it is in the root namespace.
echo "<pre>";print_r($result);

Laravel insert query :


Laravel insert multiple records :


Laravel update query example:


Laravel where clause query:

DB::table('users')->where('age', '>',10)->get();

Laravel group by query:


Laravel delete query : 

DB::table('users')->where('id', '=', 1)->delete();

Laravel truncate table :


I hope you like the post . please comment below for help or suggestion.

How to add custom class helper in laravel

In this tutorial i will show you how to create custom component helper class in laravel 5 framework. Here i'm creating CommonHelper.php class in directory app/Lib directory.

Laravel 5 Custom Class Component

Step 1: Here is your code for CommonHelper.php file.

namespace App\Lib;
class CommonHelper {
   public function getDate() {
        return date('Y-m-d H:i:s');

Step 2: Now you can add the namespace(use App\Lib\CommonHelper) of commonHelper class in your controller file where you would like to use it.

namespace App\Http\Controllers;
use App\Lib\CommonHelper;
class TestController extends Controller {
   protected $commonHelper;
   public function __construct(CommonHelper $commonHelper) {
       $this->commonHelper = $commonHelper;
  public function index() {

getDate in commonHelper is non static method.static method will be accessed using  :: (scope operator).If getDate function is static then you call it like commonHelper::getDate(). I hope you understand how to create custom class in laravel . if you find any help related to this please comment.

Friday, 7 October 2016

How to connect multiple database in Yii2

In this post i will show you how to create multiple databases in yii2.In yii2 configuration you can connect with more than one databases.

Yii2 Multiple database

Step 1: You have to add component of multiple database in your config/main.php file where you defined the connection.

'db'=> [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=dbname',
    'username' => 'username',
    'password' => 'password',
    'charset' => 'utf8'
'secondDb'=> [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=dbname2',
    'username' => 'username',
    'password' => 'password',
    'charset' => 'utf8'

Step 2: After defined the multiple database in configuration you have to use it like in controller.

$q = 'SELECT * from table where 1'; //This is sql statement
$result1 = Yii::$app->db->createCommand($q)->queryAll(); // The db is first db instance which is dbname
$result2 = Yii::$app->secondDb->createCommand($q)->queryAll(); //The secondDb is your new second db instance which is dbname2


If your are using the ActiveRecord model then you change the db name like this.


namespace api\models;

namespace api\modules\v1\models;

use \yii\db\ActiveRecord;

class User extends ActiveRecord
    public static function tableName()
        return 'user';

    public static function getDb()
        return \Yii::$app->get('secondDb'); // second database

I hope you like the post if you find any issue related the this configuration please comment below.

Thursday, 6 October 2016

Session management in Yii2 Framework

A session is a way to store information (in variables) to be used across multiple pages. In PHP you can directly use session $_SESSION it is global function of PHP.Now i want to show you how to use session in yii2 framework.yii\web\Session instance is used to access the session application component.

Yii2 Session

use  yii\web\Session;

$sessionObj = Yii::$app->session;
// check if a session is already opened
if ($sessionObj->isActive) ...
// opening a session
// closing a session
// destroys all data registered to a session.

How to set Session:
$sessionObj = Yii::$app->session;
$sessionObj->set('website', '');
$sessionObj['website'] = '';
$_SESSION['website'] = '';

How to get Session :
$sessionObj = Yii::$app->session;
$website = $sessionObj->get('website'); //
$website = $session['website']; //

How to remove session variable:
$sessionObj = Yii::$app->session;
unset($_SESSION['website']); // in php

How to check session variable is set:
$sessionObj = Yii::$app->session;
if ($sessionObj->has('website')) 
if (isset($sessionObj['website']))
if (isset($_SESSION['website'])) 

I hope you like this article please comment and share.

How to get session in Zend Framework 2

In ZF2 instead of using Sessions we should use this use ZendSessionContainer class. The Container class extends of ArrayObject and instantiates with ARRAY_AS_PROPS flag so you can easily iterate through properties.Now you need to instantiate the ZendSessionContainer class and pass a name to the constructor.

Zend 2 Session

use Zend\Session\Container;
$sessionObj = new Container('user');

Set the session :

$sessionObj->offsetSet('name', 'wantcode');

Read or Get Session Value By Key in zf2:

$name = $sessionObj->offsetGet('name');

Check session key exist:


I hope you like this article please comment and share.

Wednesday, 5 October 2016

Setting up a maintenance mode in laravel 5

In this post i will show you how to enable maintenance mode in laravel 5 framework. Sometimes you need to down your website so you should enable the maintenance mode for reflecting developement goes on.

Laravel Middleware

Enable the maintenance mode: 
php artisan down

Disable the maintenance mode: 
php artisan up

In this if you want to allow some IP's then we need to override the \vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenace Middleware.

Step 1: You can get the ip address by using $this->request->getClientIp().

Step 2: Then copy the default laravel5 maintenance middleware in \app\Http\Middleware\MaintenanceMode.php or you can named as it is like CheckForMaintenanceMode.

<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
class MaintenanceMode implements Middleware {
    protected $request;
    protected $app;
    public function __construct(Application $app, Request $request)
        $this->app = $app;
        $this->request = $request;
    public function handle($request, Closure $next)
        if ($this->app->isDownForMaintenance() &&
            !in_array($this->request->getClientIp(), ['',''])) // allowing the ip address
            throw new HttpException(503);
        return $next($request);

Step 3: Now you need to open \app\Http\Kernel.php and comment the default middleware and add new middleware on it.

<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
     * The application's global HTTP middleware stack.
     * @var array
     protected $middleware = [
          // 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
     * The application's route middleware.
     * @var array
     protected $routeMiddleware = [
          'auth' => 'App\Http\Middleware\Authenticate',
          'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
          'guest' => 'App\Http\Middleware\RedirectIfAuthenticated'

Step 4: You can change the view template for MaintenanceMode which is located in resources/views/errors/503.blade.php.

I hope you like the post and please comment below for suggestion , problem you faced during the configuration.

Monday, 3 October 2016

How to redirect http to https in laravel using middleware

In this post i will show you how to redirect all your http request to https you can do it with the help of middleware.The middleware will redirect every request to https if your environment is production or you can adjust the setting according to your need.

Laravel Middleware

Step 1: Using Command line you can create a middleware.

php artisan make:middleware HttpProtocol

Edit this file in your favourite editor and its look like this.


namespace App\Http\Middleware;

use Closure;

class HttpProtocol

    public function handle($request, Closure $next)

        if (!$request->secure() && env('APP_ENV') === 'pro') {
            return redirect()->secure($request->getRequestUri());

        return $next($request);

Step 2: Update the /app/Http/Kernel.php by adding 'App\Http\Middleware\HttpProtocol' into middleware array property.

protected $middleware = [

If you want to apply middleware only on specific routes the you need to assign middleware route by adding 'App\Http\Middleware\HttpProtocol' in $routeMiddleware array.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'forceSsl' => App\Http\Middleware\HttpProtocol::class,

Step 3: Now you can use the middleware like.

Route::get('projects', ['middleware' => 'forceSsl', function()
   echo 'welcome for https';

Hope you like the post for any help or suggestion please comment below.

Sunday, 2 October 2016

How to use mongodb in yii2 application

MongoDB is a document based database designed for scalability and agility. It stores the data in json like document instead of storing in tables and rows in relational databases like mysql.It is open source database and following are its features.

Yii2 MongoDb

MongoDB is schema less database which makes it flexible.
Dynamic schemas.
Geospatial support.
Its provides high performance.
Text search integrated.
Easy scalability.

In this post i will show you how mongodb is used in your yii2 application. In this post i'm expecting you have already installed the mongodb in your system if you not installed it then read here.

Step 1: you need to install the package library of mongodb before using it.

php composer.phar require --prefer-dist yiisoft/yii2-mongodb

or add it in your composer.json file.

"yiisoft/yii2-mongodb": "~2.1.0"

Step 2: After successfully installing the package you need to configure it in your config file.

return [
    'components' => [
        'mongodb' => [
            'class' => '\yii\mongodb\Connection',
            'dsn' => 'mongodb://developer:password@localhost:27017/yourdatabase',

Step 3: After putting the connection you can directly use it by using connection instance you may access databases and collections.

$collection = Yii::$app->mongodb->getCollection('employee');
$collection->insert(['name' => 'Mac', 'status' => 1]);

In this above command employee is your kind of table called collection in mongodb and it contains a document of name Mac in it.

Or you can also use it with model (ActiveRecord class).

use yii\mongodb\ActiveRecord;

class Employee extends ActiveRecord
     * @return string the name of the index associated with this ActiveRecord class.
    public static function collectionName()
        return 'employee';

     * @return array list of attribute names.
    public function attributes()
        return ['_id', 'name', 'email', 'address', 'status'];

In your controller you can call it like below:

Adding the namespace class in controller class.

use yii\data\ActiveDataProvider;
use yii\mongodb\Query;

For query you can use it like:

$query = new Query();
$query->from('employee')->where(['status' => 2]);
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
$models = $provider->getModels();

I hope this post is helpful for you and if you find any problem related to configuration please comment below.

Saturday, 1 October 2016

Create Validation using Scenarios in Yii2 Application

In this post i will show you how to create a simple custom validation using scenarios attribute in yii2 application.Yii2 model is designed in very flexible way for dynamic logic based on scenario. A model supports only one scenario and its named default (by default).ex on user registeration we will get username ,email and password. At the time of login we need only username and password. So the same model is using two type of validation here one is based on login and other is registeration so we can handle this using scenarios.

Yii2 Scenarios

Register Scenario - Required - username, password, email
Login Scenario - Required - username, email

Step 1: Create a model class where rules function contain this code of validation rule.

class User extends Model
    public $name;
    public $email;
    public $password;
    public function rules(){
        return [
            [['name', 'email', 'password'], 'required', 'on' => 'register'],
    public function scenarios()
        $scenarios = parent::scenarios();
        $scenarios['login'] = ['name','password'];//Scenario Values Only Accepted
        return $scenarios;

Step 2: After setting the validation rule you can call the scenarios like this.

class UserController extends Controller
    public function  actionLogin(){
        $model = new User;
        $model->scenario = 'login';
    public function  actionRegister(){
        $model = new User(['scenario' => 'register']);

For more example you can read this post in yii2 framework.I hope you like the post and please comment if you need any help related to this post.

Create custom Component in Yii2 Application

In this post i will show you how to create a simple custom component in yii2 application.

Yii2 component

Step 1: create a custom file of component in your favourite location . i'm creating it in frontend/components/Custom.php

namespace app\components;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;

class Custom extends Component
public function sayhello()
  echo "Welcome to Cutsom Component";

Step 2
: Add the custom component in your config setting file.

'components' => [
          'custom' => [
            'class' => 'frontend\components\Custom', //your file location

Step 3
: All things are done now how to use the component in your controller.

namespace app\controllers;
use Yii;
class SiteController extends \yii\web\Controller
    public function actionIndex()

I hope you like the post and please comment if you need any help related to this post.

How to send email in Yii2 framework

In this post i will show you how to send an email using yii2 framework.Actually in yii2 framework its very easy to configure your email settings in config file.Yii2 provide a easy solution for your email settings and its using yii2-swiftmailer library for by default.

Yii2 Swiftmailer

Step 1: Open your config file located in common/config/main-local.php (i'm using advanced application of yii2).Add the below code under component array.

return [
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            //'enableProfiling' => false,
            //'enableParamLogging' => true,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => '',
                'username' => '',
                'password' => '',
                'port' => '',
                'encryption' => 'tls',

useFileTransport must be changed to false and transport is set to use Swift_MailTransport in your yii2 application.

Step 2: After the configuration settings you can use it.

    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->setHtmlBody('<b>HTML content</b>')

You can also read the mailer class in yii2.I hope you like the post and please comment if you need any help related to this post.

How to create PDF in yii2 using mpdf library

mPDF is a class to generate PDF files from HTML with Unicode/UTF-8.In this post i will show you how to integrate mPDF in yii2 to genreate a pdf file from html templates.

Create PDF Using mPDF

Install mPDF Using Composer : Open your composer.json file and add a "mpdf/mpdf":"*" or you can add it directly using php composer.phar require mpdf/mpdf "dev-master" running in your console this command will add it automatically in composer.json file.

"require": {
      "php": ">=5.4.0",
      "yiisoft/yii2": "*",
      "yiisoft/yii2-bootstrap": "*",
      "yiisoft/yii2-swiftmailer": "*",

Next thing you need to do is update the composer using command:

composer update

Usage: you can directly import the library class using use mPDF; in your controller class and then crate object for mPDF. using generated object you call all of mPDF methods.

namespace app\controllers;
use mPDF;
class PdfController extends \yii\web\Controller
   // show pdf in browser                        
   public function actionIndex(){
        $mpdf=new mPDF();
    // for download it directly     
    public function actionDownloadPdf(){
        $mpdf=new mPDF();
        $mpdf->Output('nameofpdf.pdf', 'D');

This is just a example of creating a pdf of template but for advanced usage you can read the documentation of mPDF library and read the functions like creating table layout , css styling your pdf , header and footer.I hope you like the post and please comment for any kind of help and suggestions.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts