Friday, September 30, 2016

Multiple database connections in Laravel 5

Hi Everyone

Today we will learn how to do multiple database connections in laravel.

Sometimes we need to fetch data from multiple database. How can we do it in laravel? To achieve this we need to do following step.

In Laravel in config/database.php file, contains an array of all possible connections like MySQL, PostgreSQL, SQL Server.

 'connections' => [  
     'sqlite' => [  
       'driver'  => 'sqlite',  
       'database' => storage_path('database.sqlite'),  
       'prefix'  => '',  
     ],  
     'mysql' => [  
       'driver'  => 'mysql',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset'  => 'utf8',  
       'collation' => 'utf8_unicode_ci',  
       'prefix'  => '',  
       'strict'  => false,  
     ],  
     'pgsql' => [  
       'driver'  => 'pgsql',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset' => 'utf8',  
       'prefix'  => '',  
       'schema'  => 'public',  
     ],  
     'sqlsrv' => [  
       'driver'  => 'sqlsrv',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset' => 'utf8',  
       'prefix'  => '',  
     ],  
   ],  

Suppose we have to make connection for multiple database on mysql.

So we will make another array in connection like below.

 'connections' => [   
     'mysql_external' => [  
       'driver'  => 'mysql',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset'  => 'utf8',  
       'collation' => 'utf8_unicode_ci',  
       'prefix'  => '',  
       'strict'  => false,  
     ],    
   ],  

And we will use different env variable Like below.

  'mysql_external' => [  
       'driver'  => 'mysql',  
       'host'   => env('DB_EXT_HOST', 'localhost'),  
       'database' => env('DB_EXT_DATABASE', 'forge'),  
       'username' => env('DB_EXT_USERNAME', 'forge'),  
       'password' => env('DB_EXT_PASSWORD', ''),  
       'charset'  => 'utf8',  
       'collation' => 'utf8_unicode_ci',  
       'prefix'  => '',  
       'strict'  => false,  
     ],  

Now our env file look like below for database connections.

 DB_HOST=localhost  
 DB_DATABASE=testing  
 DB_USERNAME=homestead  
 DB_PASSWORD=secret  
 DB_EXT_HOST=localhost  
 DB_EXT_DATABASE=testing2  
 DB_EXT_USERNAME=homestead  
 DB_EXT_PASSWORD=secret  

To connect new database in our controller

 class TestController extends Controller  
 {  
   public function getTest()  
   {  
     $db_ext = \DB::connection('mysql_external');  
     $countries = $db_ext->table('countries')->get();  
     print_r($countries);  
   }  
 }  

So, by using above step, we can fetch and insert data from external database.

Hope it will help you.

Thanks

Friday, September 23, 2016

Token Mismatch error in Laravel

Hi Everyone

Today we are going to learn, how to solve token mismatch error on login page.

Sometimes we noticed that, on the login page of Laravel 5, when we leave this page for sometimes and then click on login button, then it shows token mismatch error.

This is because session time of laravel has been expired and current token for that page do not match the actual page.

To prevent this kind of error, we have to write below code

Open the file :  app/Exceptions/Handler.php

and add below code in render function.
  public function render($request, Exception $e)  
   {  
     if ($e instanceof \Illuminate\Session\TokenMismatchException) {  
       return redirect()->guest('auth/login');  
     }  
     return parent::render($request, $e);  
   }  

Now instead of showing token mismatch error, it will redirect to login page and refresh the token.

Thanks

Thursday, September 15, 2016

Laravel: Creating pagination using array instead of an object

Hi Everyone

Today we will going to learn, How to create pagination using array instead of an object.

Generally, In Laravel we use simplePaginate() or paginate() functions to paginate. But these function by default work on if we have an object.

Some time we need to pass an array in blade template. So how can we do pagination on array. To do this we have to use following code.

Firstly include these two lines in our controller where we want to do pagination.

 use Illuminate\Pagination\Paginator;  
 use Illuminate\Pagination\LengthAwarePaginator;  

Then make a function like below in same controller.

   public function paginate($items, $perPage)  
   {  
     $pageStart = \Request::get('page', 1);  
     $offSet = ($pageStart * $perPage) - $perPage;  
     $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);  
     return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));  
   }  

In above function first parameter is an array whom we want to paginate and second parameter is number of item we want to show per page.

Now lets see how we can use it.

In the controller suppose we have another function, from where we want to sent data to view.

 public function getData($){  
     $getData = \App\ModelName::all();  
     $dataArray = array();  
     $i=0;  
     foreach($getData as $data){  
       $dataArray[$i]['id'] = $data->id;  
       $i++;  
     }  
     $data = array('data' => $this->paginate($dataArray,'15'));  
      return view("viewName", $data);  
   }  

In blade template we have to use following line of code to show paging.

 {!! $data->render() !!}  

Hope this will help someone.

Thanks

Sunday, September 11, 2016

PHP: Exploring Regular Expression Syntax validating a phone number

Hi Everybody

Today we will learn some regular expression syntax while validating an international phone number for usa and uk.

Following are the format we are going to use an example:

+44 (1232582358)
+1 1472583695
+44 (123)(258)(2358)
+1 (123)(258)(2358)
+1 (123).(258).(2358)
+1 (123)-(258)-(2358)
+1 (123)-258-2358
+1 (0)(123)-258-2358

Seeing above format means, number always start with '+' sign and followed by 1 or 44.

So we will start our expression with \+(44|1)
After that can be space, hyphen(-) or dot (.) will come.

For that we will write ([ -\.])?
Here "?" means 0 or one of either space,hyphen or dot. 

After that some people do write (0) for their national representation. E.g
+1 (0)(123)-258-2358

Some people write some not. So either it will come at one time or not come.

For that we will write (\(0\))?, means either (0) will come one time or not come.

After that , people write their 10 digit number with bracket or without. or 4-3-3 format or 3-3-4 format with or without bracket. Some people use dot(.) or space instead of hyphen.

Below expression cover all those :

(\(?[\d]{10}\)?|(\(?[\d]{4}\)?([ -\.])*\(?[\d]{3}\)?([ -\.])*\(?[\d]{3}\)?)|\(?[\d]{3}\)?([ -\.])*\(?[\d]{3}\)?([ -\.])*\(?[\d]{4}\)?)$

I am going to explain this in step by step.

(\(?[\d]{10}\)? means any digit of whose length is 10 with or without bracket.

"|" sign represents or.

([ -\.])? represents either space , hyphen or dot will come or not come.

\(?[\d]{3}\)? means any digit of whose length is 3 with or without bracket.

After that i have use same expression with "|" sign.

And at the end of expression $ sign represents end of expression. 

Hope it will help you to understand some basic use of regular expression syntax.

Thanks





Sunday, September 4, 2016

Integrate slack recipe with deployer

Hi

Today we will learn how to integrate slack message with deployer. After completing the deployment, a message will be send to slack channel.

First, copy/download the slack recipe from given url

"https://github.com/deployphp/recipes/blob/master/recipes/slack.php", then put it into under your recipe folder.

In this page, please configure below as per your requirement.

 // slack.php
 $defaultConfig = [
     'channel' => '#your slack channel',
     'icon'   => ':sunny:',
     'username' => 'slack username',
     'message' => "Deployment to `{{host}}` on *{{stage}}* was successful\n({{release_path}})",
     'app'   => 'app-name',
   ];
After that, in our deploy.php, include this slack recipe.

 // deploy.php  
 require 'vendor/deployer/deployer/recipe/slack.php';  

after including slack recipe, please configure below setting for slack.

 // deploy.php  
 set('slack', [  
   'token' => 'your slack token',  
   'team' => 'your slack team like team.slack.com',  
   'app'  => 'mrl sandbox',  
 ]);  

Slack token can be generate from slack api website url.

Since we should only notify Slack channel of a successfull deployment, the deploy:slack task should be executed right at the end.

 // deploy.php  
 after('deploy', 'deploy:slack');