Tuesday, December 27, 2016

How to upload multiple array of images in laravel

Hi

First of all Happy New Year to all of you.

Today we will learn how to upload multiple array of images in laravel.

When we build dynamic view to add images then we put our field name in array. Like below

 <input type="file" name="images[]" accept="image/*" class="input-group">  


For saving these kind of file or images we needed a controller in laravel.

Below is my controller code for uploading files and images:

 <?php  
 namespace App\Http\Controllers;  
 use Validator;  
 use Redirect;  
 use Request;  
 use Session;  
 class FileController extends Controller {  
  public function multiple_upload(Request $request) {  
   // getting all of the images form post data  
   $fileName=$request->file('images');  
   // Making counting of uploaded images  
   $file_count = count($fileName);  
   // $uploadcount = 0;  
   foreach($fileName as $file) {  
    $rules = array('images' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc': if we want to validate specific extension  
    $validator = Validator::make(array('images'=> $file), $rules);  
    if($validator->fails()){  
     $destinationPath = public_path("/images");  
     $file = $file->getClientOriginalName();  
     $upload_success = $file->move($destinationPath, $file);  
     $uploadcount ++;  
    }  
   }  
   if($uploadcount == $file_count){  
    Session::flash('success', 'Upload successfully');  
    return Redirect::to('your_route_name');  
   }  
   else {  
    return Redirect::to('your_route_name')->withInput()->withErrors($validator);  
   }  
  }  

Thanks.


Thursday, December 15, 2016

Running Laravel Queue Listner with Supervisor

Hi

Today, we learn how to run queue listener with supervisor.

To run Laravel's queue listener, we use below command:

 php artisan queue:listen --timeout=60 --tries=3 

However this process won't be restarted when the process ends. So We have to use Supervisor to keep this queue listener process active at all times. Below are instructions for Ubuntu

Install Supervisor with following command

 sudo apt-get install supervisor

Ensure it's started with

 sudo service supervisor restart

Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, we may create any number of configuration files that instruct supervisor how our processes should be monitored. For example, let's create a laravel-queue.conf file that starts and monitors a queue:listen process:

To create laravel_queue.conf file, run following command

 sudo nano /etc/supervisor/conf.d/laravel_queue.conf

 [program:laravel_queue]
 process_name=%(program_name)s_%(process_num)02d
 command=php /home/username/path_to_laravel/artisan queue:listen --timeout=60 --tries=2
 autostart=true
 autorestart=true 
 user=username 
 stderr_logfile=/var/log/laraqueue.err.log
 stdout_logfile=/var/log/laraqueue.out.log 
 

Now give it execute permissions:

 chmod +x /etc/supervisor/conf.d/laravel_queue.conf

Once the configuration file will be created, we update the Supervisor configuration and start the processes using the following commands:

 sudo supervisorctl reread  
 
 sudo supervisorctl update
 
 sudo supervisorctl start laravel-worker:*  

Below 2 command are necessary, whenever we will change our configuration file.

 sudo supervisorctl reread  
 sudo supervisorctl update  

Thanks

Thursday, December 8, 2016

Time Synchronisation with NTP

Last week working on one of project, I found that my server UTC time is running 2 min 30 seconds behind actual UTC time.

I asked one of my senior and he told me to run following command :

 sudo ntpdate pool.ntp.org  

This gave me the desired result and my server time is synched with actual UTC time.

After that I googled the command and found more facts about this.

What is NTP

NTP (Network Time Protocol)  is a TCP/IP protocol for synchronising time over a network. Basically a client requests the current time from a server, and uses it to set its own clock.

For fixing the time I run the "ntpdate" command but "ntpdate" is not an action that should be taken regularly because it syncs the virtual server’s time so quickly, the jump in time may cause issues with time sensitive software. Therefore, it is best to run this only once, prior to setting up NTP, and then let NTP take over—otherwise, if the server’s time is too far off, NTP may not launch altogether.

Installing the NTP

To download or install NTP, run the following command on Ubuntu

 sudo apt-get install ntp  

Configuring the NTP Servers

After installing, open the following configuration file

 sudo nano /etc/ntp.conf  

It will show the lists of NTP Pool Project servers like below

 server 0.ubuntu.pool.ntp.org;  
 server 1.ubuntu.pool.ntp.org;  
 server 2.ubuntu.pool.ntp.org;  
 server 3.ubuntu.pool.ntp.org;  

Each line then refers to a set of hourly-changing random servers that provide our server with the correct time. The servers that are set up are located all around the world, and we can see the details of the volunteer servers that provide the time with the following command

 ntpq -p  

This command will output like below

  remote      refid   st t when poll reach  delay  offset jitter  
 ================================================================  
 -mail.fspproduct 209.51.161.238  2 u  50 128 377  1.852  2.768  0.672  
 *higgins.chrtf.o 18.26.4.105   2 u 113 128 377  14.579  -0.408  2.817  
 +mdnworldwide.co 108.71.253.18  2 u  33 128 377  47.309  -0.572  1.033  
 -xen1.rack911.co 209.51.161.238  2 u  44 128 377  87.449  -5.716  0.605  
 +europium.canoni 193.79.237.14  2 u 127 128 377  75.755  -2.797  0.718  

Although these servers will accomplish the task of setting and maintaining server time, we can set our time much more effectively by limiting the ntp to the ones in our region (europe, north-america, oceania or asia), or even to the ones in our country, for example in America:

 us.pool.ntp.org  

We can find the list international country codes (although not all of the countries have codes) here

Once all of the information is in the configuration file, restart ntp with following command:

 sudo service ntp restart  

NTP will slowly start to adjust the virtual private server’s time.

Thanks

Sunday, November 27, 2016

Swagger implementation in laravel 5

Hi Everybody

Today we will learn how to integrate swagger into laravel 5.

Swagger creates the RESTful contract for our API, detailing all of its resources and operations in a readable format for easy development and integration.

Installation

For Swagger 2.0

 composer require "darkaonline/l5-swagger:~3.0"  

Open your AppServiceProvider (located in app/Providers) and add this line in register function

  $this->app->register(\L5Swagger\L5SwaggerServiceProvider::class);  

open your config/app.php and add this line in providers section

 \L5Swagger\L5SwaggerServiceProvider::class  

Configuration

 Run php artisan l5-swagger:publish to publish everything  
 Run php artisan l5-swagger:publish-config to publish configs (config/l5-swagger.php)  
 Run php artisan l5-swagger:publish-assets to publish swagger-ui to your public folder (public/vendor/l5-swagger)  
 Run php artisan l5-swagger:publish-views to publish views (resources/views/vendor/l5-swagger)  
 Run php artisan l5-swagger:generate to generate docs or set generate_always param to true in your config or .env file  

Now open your controller and write following script above class definition to define basic information about your api.

 /**  
  * @SWG\Swagger(  
  *   schemes={"http","https"},  
  *   host="dev.eduru.com",  
  *   basePath="/",  
  *   @SWG\Info(  
  *     version="1.0.0",  
  *     title="This is my website cool API",  
  *     description="Api description...",  
  *     termsOfService="",  
  *     @SWG\Contact(  
  *       email="contact@mysite.com"  
  *     ),  
  *     @SWG\License(  
  *       name="Private License",  
  *       url="URL to the license"  
  *     )  
  *   ),  
  *   @SWG\ExternalDocumentation(  
  *     description="Find out more about my website",  
  *     url="http..."  
  *   )  
  * )  
  */  
 class ProductController extends Controller  


Write following script above your function where you have defined your api functionality.

 /**  
    * @SWG\Get(  
    *   path="/api/v1/products",  
    *   description="Returns all pets from the system that the user has access to",  
    *   operationId="findPets",  
    *   produces={"application/json", "application/xml", "text/xml", "text/html"},  
    *   @SWG\Parameter(  
    *     name="tags",  
    *     in="query",  
    *     description="tags to filter by",  
    *     required=false,  
    *     type="array",  
    *     @SWG\Items(type="string"),  
    *     collectionFormat="csv"  
    *   ),  
    *   @SWG\Parameter(  
    *     name="limit",  
    *     in="query",  
    *     description="maximum number of results to return",  
    *     required=false,  
    *     type="integer",  
    *     format="int32"  
    *   ),  
    *   @SWG\Response(  
    *     response=200,  
    *     description="pet response",  
    *     @SWG\Schema(  
    *       type="array",  
    *       @SWG\Items(ref="#/definitions/pet")  
    *     ),  
    *   ),  
    *   @SWG\Response(  
    *     response="default",  
    *     description="unexpected error",  
    *     @SWG\Schema(  
    *       ref="#/definitions/errorModel"  
    *     )  
    *   )  
    * )  
    */  
 /**  
    * Display a listing of the resource.  
    * 
    */  
   public function getProducts()  
   {  
     //  
   }  


Now run follwoing command to publish.

 php artisan l5-swagger:publish  

Now open following link in your browser

http://yourdomain.com/api/documentation

In above link, we can see our api documentation and its implementation.

Thanks

Sunday, November 20, 2016

Filesystem in laravel

Hi

Today we will learn, how to store file in laravel.

Laravel framework comes with built in storage handling which is compatible with a variety of systems. It is built upon the popular library Flysystem and therefore integrates with lots of services via the same common interface.

Storage configuration resides in the “config/filesystems.php” file. We can add multiple engines such as local drives and cloud drives.

Basic file operations

The filesystem integration provides a straight forward way of interacting with files. Basic write/read operations are illustrated below.

 // Write content to file  
 $content = 'File content ...';  
 Storage::put( 'my_file.txt', $content );  
 // Read content from file  
 $content = Storage::get( 'my_file.txt' );  
 // Delete file  
 Storage::delete( 'my_file.txt' );  
 You can also append/prepend content easily to existing files.  
 // Append content to file  
 $append = 'Appended text...';  
 Storage::append( 'my_file.txt', $append );  
 // Prepend content to file  
 $prepend = 'Prepended text...';  
 Storage::prepend( 'my_file.txt', $prepend );  

Listing files and directories

Sometimes we need to read your file structure which can be done with the listing methods.
We can list both files and directories in one level or recursively.

 // List all files in directory  
 $files = Storage::files($directory);  
 // List all files & directories in directory  
 $files = Storage::allFiles($directory);  
 // List all directories in directory  
 $directories = Storage::directories($directory);  
 // List all directories recursively in directory  
 $directories = Storage::allDirectories($directory);  


Thanks

Thursday, November 10, 2016

Laravel: Touching Parent Timestamps

Hi

Today we will learn how to use Touch property/method in Laravel Eloquent.

Sometime we need to update parent's model timestamp when the child model is updated.

When a model belongsTo or belongsToMany another model, such as a Comment which belongs to a Post, it is sometimes helpful to update the parent's timestamp when the child model is updated.

For example, when a Comment model is updated, we may want to automatically "touch" the updated_at timestamp of the owning Post. Laravel Eloquent makes it easy. We need to add a touches property containing the names of the relationships to the child model.

 <?php  
 namespace App;  
 use Illuminate\Database\Eloquent\Model;  
 class Comment extends Model  
 {  
   /**  
    * All of the relationships to be touched.  
    *  
    * @var array  
    */  
   protected $touches = ['post'];  
   /**  
    * Get the post that the comment belongs to.  
    */  
   public function post()  
   {  
     return $this->belongsTo('App\Post');  
   }  
 }  

Now, when we update a Comment, the owning Post will have its updated_at column updated as well:

 $comment = App\Comment::find(1);  
 $comment->text = 'Edit to this comment!';  
 $comment->save();  

Thanks


Sunday, October 23, 2016

Laravel 5.3 : Integration of API Authentiation (Passport)

Hi Everybody

Today we will learn how to itegrate Passport in laravel 5.3 and generate tokens password grant client. Laravel Passport provides a full OAuth2 server implementation for our Laravel application. APIS do not maintain session state between requests. So we need a tokens to Authenticate users. 

Step 1 : Go to your project folder and Install Passport via the Composer package manager with following command.

 composer require laravel/passport  

Step 2 : Register the Passport service provider in the providers array of  yourconfig/app.php configuration file:

Laravel\Passport\PassportServiceProvider::class,
Step 3 : The Passport service provider registers its own database migration directory with the framework, so we should migrate our database after registering the provider. The Passport migrations will create the tables our application needs to store clients and access tokens:

php artisan migrate
Step 4 : We should run the passport:install command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:

php artisan passport:install

Step 5 : After running this command, add the Laravel\Passport\HasApiTokens trait to our App\User model. This trait will provide a few helper methods to our model which allow us to inspect the authenticated user's token and scopes:

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
Step 6 : We should call the Passport::routes method within the boot method of our AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}
Step 7 : Finally, in our config/auth.php configuration file, we should set the driver option of the api authentication guard to passport. This will instruct our application to use Passport's TokenGuard when authenticating incoming API requests:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],
Above step also mentioned in laravel official document for installing Passport.

Now go to your controller, where we want to generate access and refresh token. Inside the controller write the following script.

 $http = new GuzzleHttp\Client();  
 $oauth_client = DB::table('oauth_clients')->where('name', '=', 'Laravel Password Grant Client')  
   ->where('password_client', '=', 1)->first();  
 $response = $http->post(url('/') . '/oauth/token', [  
   'form_params' => [  
     'grant_type' => 'password',  
     'client_id' => $oauth_client->id,  
     'client_secret' => $oauth_client->secret,  
     'username' => $request->email,  
     'password' => $request->password,  
     'scope' => '',  
   ],  
 ]);  
 $response_body = json_decode((string)$response->getBody(), true);  
 $access_token = $response_body['access_token'] ;  
 $refresh_token = $response_body['refresh_token'];  

Now token is generated through password grant client.

Thanks



Saturday, October 8, 2016

Laravel ajax and 500 internal server error

Hi Everyone

Today, we will learn what are the reason and their solution behind the 500 internal server error when using ajax in laravel. Sometimes when we use ajax with Laravel, it gives 500 internal server error. Following are the reasons:

CSRF:

The common reason behind 500 internal server error is missing CSRF token. In Laravel, CSRF token is required for all forms. People generally forget submitting the token with ajax request. Submitting token less ajax request results in 500 internal server error.

To fix this,  just add a hidden field in the form. Below is the code for us to add in our form:

1. For Blade Template Users:

 <input type="hidden" name="_token" value="{{ Session::token() }}">  

2. For non Blade Users:

 <input type="hidden" name="_token" value="<?php Session::token() ?>">  

3. Directly as ajax data:

 var request = $.ajax({  
  url: "test.php",  
  method: "POST",  
  data: { _token : <?php Session::token() ?>},  
  dataType: "html"  
 });  

This will solve your problem.

Other reason for this might be

WRONG ROUTE:

You may be submitting ajax data to wrong route type and even wrong url (404). So first double check the path you are submitting to. Second, check whether the route accepts “Post” or “Get” data type.
Because submitting post data via Get method or vice versa will results in Laravel ajax giving 500 Internal Server Error.

DATA TYPE RETURNED:

If you are returning Boolean and your ajax code is set for Json or any other data type then chances are that you will get internal server error. Try to set data type for all ajax response to json. If you are using jQuery then set dataType to xml.

 var request = $.ajax({  
  url: "/action",  
  method: "POST",  
  data: { id : userId },  
  dataType: "json"  
 });  

CROSS DOMAIN CONFIGURATION:

If you are using ajax for cross domain requests then be sure that you are sending proper headers.
In case of jQuery, just set the crossDomain variable to true. Alternatively set dataType to “jsonp”

.HTACCESS

Check your .htaccess file for any error specially after you have edited it.

Hope this will help someone.

Thanks


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');  

Saturday, August 27, 2016

Laravel : how to use query scopes

Hi

Today we will learn how and where to use query scopes.

Some times we are repeating a code snippet or a condition a number of times. Suppose we have to find a list of users who are active and a user  which is active. In controller generally we will write
 <?php  
 class UserController extends BaseController {  
   // finding list of users who are active.  
   public function listUsers() {  
    $users = User::where('active', 1)->get();     
   }  
   // finding a user detail which is active.  
   public function userDetail($id) {  
    $user = User::where('active', 1)->find($id);   
   }  
 }  
 ?>  

As we can see, the where() condition checks "if active is" repeated twice.

To prevent this, in Laravel, we can use query scopes. Query scopes are single functions that help us reuse the logic in Models. Let’s define a query scope in Model and change the Controller method as follows:

 <?php  
 //Model File  
 Class User extends Eloquent {  
   //We've defined a Query scope called active  
   public function scopeActive($query) {  
    return $query->where('active', 1);  
   }  
 }  
 //Controller File  
 class UserController extends BaseController {  
   // finding list of users who are active.  
   public function listUsers() {  
    $users = User::active()->get();  
   }  
   // finding a user detail which is active.  
   public function userDetail($id) {  
    $user = User::active()->find($id);  
   }  
 }  
 ?>  

As we can see, we’ve defined a method called scopeActive() in Model, which is prefixed with the word scope and CamelCased. This way, Laravel can understand that it’s a query scope, and we can use that scope directly. As we can see, the conditions in the Controller have also changed. They have changed from where('active', 1) to active().

Thanks

Friday, August 19, 2016

Laravel : Customizing the default Error Page

Hi everyone

Today we will learn how to customize the default error page in laravel

We all know the famous "Whoops, looks like something went wrong." page, now what if we can easily customize this to match our overall template. All we need to do is modify the default app/Exceptions/Handler.php file and override the convertExceptionToResponse method:

<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;

class Handler extends ExceptionHandler
{
    /**
     * Convert the given exception into a Response instance.
     *
     * @param \Exception $e
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function convertExceptionToResponse(Exception $e)
    {
        $debug = config('app.debug', false);

        if ($debug) {
            return (new SymfonyDisplayer($debug))->createResponse($e);
        }

        return response()->view('errors.default', ['exception' => $e], 500);
    }
}

Now we can easily customize errors.default view located under resources/view/errors folder to our application need.

We still include the original error page when using APP_DEBUG=true for development, but we can remove those line if we don't want it.

Monday, August 8, 2016

Laravel Log files by date

Hello everyone

Today we will discuss about laravel logging system.

Laravel logging mechanism is pretty simple – it writes all the errors to a file at /storage/logs/laravel.log. It’s convenient until the file gets bigger. And then we have a problem to find a bug from yesterday or some days ago. How can we solve this?

When we want to see log in laravel then we SSH to our server, go to /storage/logs folder and run ls -l command for the files list with information. And see this:

-rw-rw-r-- 1 forge forge 31580639 Jul  4 07:52 laravel.log

From above log files, it is very difficult to find log for a specific day. But it is very easy to change from single log file to daily basis log file. it’s only one setting in config/app.php file:

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Settings: "single", "daily", "syslog", "errorlog"
    |
    */

    'log' => env('APP_LOG', 'single'),

As we can see, by default the value is single file, but we can change it to daily or others – either in the config file itself, or in environment file .env.

When we change the setting to daily, instead of one laravel.log – we will get separate file for each date – something like laravel-2016-08-07.log.

Saturday, July 30, 2016

Laravel : How to get user's tweets in json

Hi

Today we will learn how to get a user's tweets in json format in laravel 5.

Add the below line of code in your composer.json file.

{
    "require": {
        "j7mbo/twitter-api-php": "dev-master"
    }
}

And then update your composer with composer update command in your terminal.

Then in any controller where you want to get tweets, use below function.

public function twitter(){
        
        $settings = array(
            'oauth_access_token' => 'Your oauth access token',
            'oauth_access_token_secret' => 'Your oauth access token secret',
            'consumer_key' => 'Your consumer key',
            'consumer_secret' => 'Your consumer secret'
        );
        $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
        $getfield = '';
        $requestMethod = 'GET';


                $twitter = new \TwitterAPIExchange($settings);
                $feeds = $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest();

        return json_encode($feeds);
        

    }


Please click or goto url https://themepacific.com/how-to-generate-api-key-consumer-token-access-key-for-twitter-oauth/994/, to generate your settings.

In above script if we use $getfield = '?user_id={user_id}', it will give tweets of that particular user. If it is left blank then it will give tweets of that user whom oauth access token belongs to. If you want to explore more then please goto url https://dev.twitter.com/rest/reference/get/statuses/user_timeline.

Hope it will help someone.

Thanks

Friday, July 22, 2016

Service Container in laravel 5

Hi

Today, we learn service container in larave 5.2

The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.


<?php

namespace App\Jobs;

use App\User;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Bus\SelfHandling;

class PurchasePodcast implements SelfHandling
{
    /**
     * The mailer implementation.
     */
    protected $mailer;

    /**
     * Create a new instance.
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Purchase a podcast.
     *
     * @return void
     */
    public function handle()
    {
        //
    }
}


In this example, the PurchasePodcast job needs to send e-mails when a podcast is purchased. So, we will inject a service that is able to send e-mails. Since the service is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the mailer when testing our application.

Thanks.

Saturday, July 16, 2016

PHP Dependency Injection with Laravel 5

Hi
Today, we will learn dependency injection in laravel.
In laravel 5, We can inject services or classes. These dependency injection techniques are very useful when we generating a large scale projects. Class dependencies are injected into the class through the constructor or setter methods.
Dependency solutions through service container simplifies the dependency injection logic for our controller by configuring the container. This really becomes crystallise if one class depends on a service, that service depends on other services and those services could also depend on more services, the container will manage that dependency results.
Example of container App/Repositories/BookDbRepository
<?php namespace App\Repositories;
use App\Book;
class BookDbRepository {
    public function all(){
       return Book::all();
    }
    public function insertData($requestData){
        $book = new Book;
        $book->title= $requestData['title'];
        $book->description= $requestData['description'];
        $book->author= $requestData['author'];
        $book->save();
    }
    public function updateData($id, $requestData){
        $book = Book::find($id);
        $book->title = $requestData['title'];
        $book->description = $requestData['description'];
        $book->author = $requestData['author'];
        $book->save();
    }
    public function deleteData($id){
        Book::find($id)->delete();
    }
}
Into BookDbRepository we can see 4 methods are specifies show, insert, update and delete. Where container has all power to change the database. Unfortunately, controller will talk to BookDbRepository for every new query requests of application.
After early changes, Lets see what effects has been done in our controller BookController class.
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\BookDbRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
class BookController extends Controller {
    protected $repo;
    public function __construct(BookDbRepository $repo)
    {
        $this->repo = $repo;
    }
public function index()
{
$allBooks = $this->repo->all();
        return View('books.bookList', compact('allBooks'));
}
public function store(PublishBookRequest $requestData)
{
        $this->repo->insertData($requestData);
        return redirect()->route('book.index')->with('message', 'New record has been added!');
}
public function update($id, PublishBookRequest $requestData)
{
        $this->repo->updateData($id, $requestData);
        return redirect()->route('book.index')->with('message', 'Record has been updated!');
}

public function destroy($id)
    {
        $this->repo->deleteData($id);
        return redirect()->route('book.index')->with('message', 'Record deleted successfully!');
    }
}
Clearly we can see that in constructor of class BookController , we have injected the instance of BookDbRepository class.
Thanks

Friday, July 8, 2016

Laravel 5.2 and MySQL dates

Hi

Today we will learn, how to use MySQL dates with laravel 5.2.

Starting with MySQL 5.7, 0000-00-00 00:00:00 is no longer considered a valid date, since strict mode is enabled by default. All timestamp columns should receive a valid default value when we insert records into our database. We may use the useCurrent method in our migrations to default the timestamp columns to the current timestamps, or we may make the timestamps nullable to allow null values:

$table->timestamp('foo')->nullable();

$table->timestamp('foo')->useCurrent();

$table->nullableTimestamps();

Thanks