Tuesday, August 23, 2016

Install laravel 5.3 in Ubuntu 14.04


Once again Laravel comes with many amazing features and i can't wait more to try this all out.

In this post i am going to write how to setup laravel 5.3 in Ubuntu 14.04.
I am planning on making video for each of this post. Here you can find more about installation of l5.3 on ubuntu
In laravel documentation, it says
  • PHP >= 5.6.4
required to install laravel 5.3.

So first run following command on terminal:

  • php -v
This will show you, your current php version.


As you can see, i have PHP version 5.5.9 , so i have to upgrade it to  >=v5.6.4

So to do this i have to run following commands:

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php5-5.6
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install php5
Now if i check my updated php version i can see this :


So my php version updated as i needed.

Now i have to run following command to install new Laravel 5.3 setup

composer create-project --prefer-dist laravel/laravel HighFive
So my installation is done.

Now i have to go to project directory and run following command
php artisan serve
Now if i go to browser and browse localhost:8000 , hurry laravel 5.3 is on..


Laravel Elixir Setup and Uses



Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel application. Elixir supports several common CSS and JavaScript pre-processors, and even testing tools. Using method chaining, Elixir allows you to fluently define your asset pipeline. For example:
elixir(function(mix) {
    mix.sass('app.scss')
       .coffee('app.coffee');
});
Gulp is a task/build runner for development. It allows you to do a lot of stuff within your development workflow. You can compile sass files, uglify and compress js files and much more.

Installation & Setting Up

  • First Setup Node
    • Try Following command to check node version
      • node -v 
          
  • Install Gulp Globally
    • Try Following command 
      • npm install --global gulp-cli (for windows)
      • sudo npm install --global gulp-cli (for linux)
      • npm install -- (to install npm dependency: use sudo for linux do install all dependency)
After   Installing all dependency , run following code to notify all changes related to app.scss or any file your are willing to work.







  • gulp watch 
  • Lets say, we want to make change to app.scss and convert it to css file under public folder.
    To do this, first change 
    elixir(function(mix) {
        mix.sass('app.scss')
           .coffee('app.coffee');
    });
    to

    elixir(function(mix) {
        mix.sass('app.scss','public/style.css');
    });
    now change code in app.scss file and you'll see all changes in public/style.css file.

    Sunday, August 14, 2016

    Integrate Redis on Laravel 5.2

    In this tutorial i am going to write basic steps to integrate Redis with laravel 5.2 

    Steps

    First

    Install Redis server on your system.

    I am using  Ubuntu 14.04. Following commands will setup Redis Server on your machine.



    sudo add-apt-repository ppa:chris-lea/redis-server
    
    sudo apt-get update
    
    sudo apt-get install redis-server
    
    Now start Redis server using following command
    sudo service redis-server start
    
    If everything is okay, you'll see this message on Terminal
    Starting redis-server: redis-server
    
    For windows user, you can find details about installation in here After successfully installing Redis server on your system, now we have to integrate it with Laravel 5.2 project.
    To do that, we need to install predis/predis package  via composer.
    Go to your project directory and from terminal run this command
    composer require predis/predis
    After installing predis/predis package via composer, we have to configure it.
    Now open .env file in a text editor and add following line at the buttom.

    #CACHE_DRIVER=redis
    #SESSION_DRIVER=redis
    CACHE_DRIVER=file
    SESSION_DRIVER=file
    QUEUE_DRIVER=sync
    
    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6379
    You can change it depending on your system's environment.
    Now our integration is done and it's time to test it.

    To test it, go to routes.php file and add following line
    use Illuminate\Support\Facades\Redis;
    Now add following line
    Route::get('redis/test',function(){
        $redis = Redis::connection();    
    $views=$redis->incr('view');
        dd($views);});
    Now run following command on terminal:
    sudo service redis-server start
    
    php artisan serve
    After starting project, open your browser and browse
    localhost:8000/redis/test
    Now you'll notice , every time you browse this url, value showing on browser always incremented by one.

    Saturday, August 13, 2016

    Opencart 2.3 landing page Bisection

    I am new to opencart 2.3 and i am learning through debugging how this e-commerce platform working.

    In this post , i am writing about changing landing page which is changing route common/home to something new. i.e uncommon/home

    I have been trying to find the root from where opencart 2.3 is routing to common/home.  After few hours (i am slow at learning but persistent )i found that the default route is found from system/config/default.php file.

    If you look carefully , you can see
    $_['action_default']        = 'common/home';
    this line.
    So if we change  the value of
    $_['action_default']
    then we can route to different landing page.

    Now, my intention was to setting up different landing page and the test route was decided as  uncommon/home.

    To make it work, first i copied all the files from catalog/controller/common directory to a new directory called catalog/controller/uncommon.

    Now change all the class name under catalog/controller/uncommon directory as follow:
    • Cart.php file
          ControllerCommonCart to ControllerUncommonCart 
    • column_left.php file
        ControllerCommonColumnLeft to ControllerUncommonColumnLeft
    Now replace all occurrence of common common with uncommon.

    Do exactly same for all other files under uncommon directory.


    Now lets create view files for all these controller to show data.

    Go to catalog/view/theme/default/template directory.

    Copy all files from catalog/view/theme/default/template/common  to catalog/view/theme/default/template/uncommon directory.

    So our basic setup completed. Now we'll change default route to our new created route.

    To do so, we have to change value of 
    $_['action_default'] as  'uncommon/home'

    Finally Login as admin in your projec and go to layouts section.
    Select home and click edit button.
    Now change the route
    'common/home' to 'uncommon/home'
    Now we are done our all set up.
    If we browse our project's landing directory, we'll see our newly created pages which are showing by routing
    'uncommon/home'
    Now change the files under uncommon directory as you like and reload browser to see the updates.

    Setting up header to collect data from API

    Get data from api Set header :
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
    header('Access-Control-Allow-Credentials: true');
    
    now get Get data using method : get or post from front end.

    Basic Git command and remotely update to Github

    In this tutorial i’ll write basic git command to create local git repository , staging changes, committing and push changes to remote git repository.


    First, We have to know what is git?
    Git is a open source distributed version control system.It is free and designed to handle everything from small to very large projects with speed and efficiency.
    
    Now one question may arise on our mind. What is version control system?
    well, Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.
    
    Now we know what is git and why we must use it.
    Our next step would be setting up git in our local machine.

    Setup Git

    *Linux
    sudo apt-get install git
    
    *Windows
    Simply download the installer exe file from the GitHub page, and run it. Git installer
    Lets start working with git!
    1. Empty Git Repository Setting Up
      To initialize a empty git repository in local machine first you have to go the directory where you want to create repository. Then write this command in terminal.

      git init

      enter image description here
    2. Check current Status of repository
      After initializing empty repository lets check current condition of repository.To do so, type this command in command line

      git status
    enter image description here

    3. Adding changed file to commit
    In our last step we created a file called helloGit.html and checked status whether it shows update or not. Now we will add this html file to stage state so that we can track further change happen to it.
    How can we do that? Write this command on terminal
    git add helloGit.html
    
    Now check current status using previous command
    enter image description here


    4. Now Committing new this change with a hints
    Now we have to keep information about this change so that we differentiate it with previous changes. To do that, write this command in terminal.
    git commit -m "Creating helloGit.html page"
    
    enter image description here
    Now lets check current git repository status using git status
    and we will see this
    enter image description here

    5. Now we’ll push it to github.com
    In this step we’ll push our updates to github.com.
    To do that we have to create a repository in github.com.
    Go to github.com and create a new repository name basicGitCommands
    Now to connect basicGitCommand repository from our local machine , we have to set it as origin.To do that, we have to write this command.
    git remote add origin https://github.com/shuvrow/basicGitCommand.git
    
    Here shuvrow is my user name. Replace it with your user name.
    After writing this command we will see this in terminal.
    If you want to create repository from your local machine using command line, write this command in terminal
    curl -u 'shuvrow' https://api.github.com/user/repos -d '{"name":"basicGitCommand"}'
    
    Now we have external git repository in github.com. So all we’ll going to push it in github.com
    To do this, we have to write this command in terminal.
    git push origin master
    
    enter image description here
    Yes!!! we have done it!
    Here is the view of github.com/shuvrow/basicGitCommand.git
    enter image description here

    Laravel Project Setup Using Composer

    In this tutorial i’ll write the key points that are necessary to create a laravel project/setting a laravel project with the help of composer.

    Composer Setup

    First We have to understand what is composer?
    Well, Composer is a tool used in PHP for dependency management. It allows us to declare the dependent libraries our project needs and it will install them in our project for us.
    Basically we tell composer about the files our project requires and composer will find these files for us.
    Composer does this in two ways.Which are :
    1.Finding the appropriate version of the file
    2.Install them for us
    Now, we need to set up composer in order to create a new Laravel project.
    We can set up composer in two ways in our local machine: Locally or globally.

    Locally setting up composer for *nix system

    1. Run the following command in terminal
    curl -sS https://getcomposer.org/installer | php
    if it fails we can download the installer with php instead,
    php -r "readfile('https://getcomposer.org/installer');" | php
    we can install composer in a specific directory using –install-dir option and providing a target directory
    curl -sS https://getcomposer.org/installer | php -- --install-dir=bin
    Globally setting up Composer
    2. Run the following code In terminal
    curl -sS https://getcomposer.org/installer | php
    Now move the composer.phar file to /usr/local/bin/composer directory using the following command
    mv composer.phar /usr/local/bin/composer
    Now you can run composer from your terminal without using
    php composer.phar
    just run composer
    That’s it!
    Window’s Installation
    In windows you have to download composer and install it like other software.
    Download composer from this link Composer
    Now Install it. After installing Composer find composer.phar file and copy it to your laravel project. You can download Laravel framework here.
    Laravel Framework

    Laravel Set Up in Windows

    Now unzip the downloaded file.Copy composer.phar file here.
    Then run this command in command line
    php composer.phar install

    Laravel Set Up in Linux


    Now you have composer set up in your machine.
    Now we will create a new laravel project using composer.
    Write the following command in your terminal and see the magic of composer!!!
    composer create-project laravel/laravel your-project-name --prefer-dist
    Now you’ll see that composer will download and set up all the necessary files required for laravel project.
    Instead of using your-project-name , use your other name as project name.
    .

    Running laravel

    Now you have a laravel project created by composer. To start building application , first you have to give read write permission to /app/storage directory in your project (Linux).
    In linux environment, you can do that using chmod command.
    Now go to the project directory from command line. You can do that by using cd command.
    Then run this command:
    php artisan serve
    You can see that you got a local server running on port 8000.
    After that go to the web browser and write localhost:8000
    Note
    8000 is the port number where my local server is running. You can change the port number if you like. Use this command to change the port number
    php artisan serve --port=8080
    You can use other number as port number.
    Now you will see a welcome message notifying you that laravel framework is working fine in your machine.

    Install LAMP and PHPmyAdmin && PHPpgAdmin on Ubuntu 14.04

    Install LAMP

    Steps are:
    1. sudo apt-get update
    2. sudo apt-get install apache2
    3. sudo apt-get install mysql-server php5-mysql
    4. sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
    5. sudo gedit /etc/apache2/conf-available/serve-cgi-bin.conf Add this line at the end of the file:
        1. ServerName localhost
       
    6. save this file
    7. sudo service apache2 restart
     

    Install PHPmyAdmin

    Steps are :
    1. sudo apt-get install phpmyadmin
    2. sudo php5enmod mcrypt
    3. sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin
    4. sudo service apache2 restart
     

    Install PHPpgAdmin

    Steps are :
    1. sudo apt-get install phppgadmin
    2. sudo gedit /etc/apache2/conf.d/phppgadmin
      • uncomment this line allow from all
    3. sudo ln -s /usr/share/phppgadmin /var/www/phppgadmin
    4. sudo cp /etc/apache2/conf.d/phppgadmin /etc/apache2/conf-enabled/phppgadmin.conf
    5. sudo gedit /etc/phppgadmin/config.inc.php
      • set $conf['extra_login_security'] = true; to false
    6. sudo service apache2 restart

    Laravel 5.2 Implicit model binding

    In Laravel 5.2 new feature called implicit model binding added. Which can be implement efficiently and in a very easy manner. Here how its done :
    1. In your routes.php file create a new route
      Route::get('user',function(){});
    2. Now if you want to retrieve information of a particular user, modify your user route as follow
      Route::get('user/{user}',function(App\User $user){ return $user; 
      });
    Now if you browse your defined route , localhost:8000/user/1
    (Assuming your laravel application running on localhost, port 8000 and you have data on your user table)
    This will return information in JSON format of the user who has id 1.
    Here , App\User is the namespace for User model.

    Laravel 5.2 using queue to send email

    To sent email after desired number of second, first change the .env file as follow.
    • First provide database credential
    • set
      QUEUE_DRIVER=sync to
      QUEUE_DRIVER=database
    Normally , QUEUE_DRIVER=sync tries to sent email immediately and if we set it as database, we can sent email after desired number of seconds. then,
    • give the email credential , from which you want to sent email
    Here i will be using smtp server , so to sent email we have to change gmail setting and give permission to access email account from less secured apps. Here is the link to set access from less secure apps click turn on and you are ready to go. Now go tho the queue.php file in config folder and find the array key database. Here is the information we get:
    'database' => [
        'driver' => 'database',
        'table'  => 'jobs',
        'queue'  => 'default',
        'expire' => 60,
    ],
    
    From this data, we can see that to use database as queue driver we have to create a table called jobs. To create this table, we have to run following command
    php artisan queue:table
    This command will create a migration file which will create a table called jobs with necessary fields. Now we will create a table to track failed jobs. To create this table we have to run following command:
    php artisan queue:failed-table
    
    This command will create a migration file , which will create a new table called failed_jobs Now run following command to create table using this migration files.
    php artisan migrate
    Now, in your .env file set following information
    MAIL_DRIVER=smtp
    #MAIL_HOST=mailtrap.io
    MAIL_HOST=smtp.gmail.com
    MAIL_PORT=587
    MAIL_USERNAME=*********
    MAIL_PASSWORD=*********
    MAIL_ENCRYPTION=tls
    MAIL_FROM=*********
    MAIL_NAME=Dushor Alo
    Now go to mail.php file on config folder. Comment out this line
    'from' => ['address' => null, 'name' => null],
    
    and use this code
    'from' => ['address' => env('MAIL_FROM'), 'name' => env('MAIL_NAME')],
    And other settings are
        'username' => env('MAIL_USERNAME'),
        'password' => env('MAIL_PASSWORD'),
        'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    
    Now go to routes.php file and add following lines
    Route::get('send/mail',function(){
        $user=['name'=>'Rashed','email'=>'xyz@gmail.com'];
    
        \Illuminate\Support\Facades\Mail::later(5,'emails.reminder', ['user' => $user],function ($m) use ($user) {
            $m->from(env('MAIL_FROM'), 'Your Testing Application');
    
            $m->to($user['email'], $user['name'])->subject('Your Reminder!');
        });
    });
    In here we are using Mail::later(5), which represents that email will be sent 5 seconds later. So our setup is done , and if we browse send/mail we will receive email after 5 seconds.

    Laravel 5.2 queuing Event listeners

    First , we need to create Event and to listen event, we also have to create listener. To do this , laravel provides us several ways. The easiest way to create event and corresponding listener we can use this command
    php artisan event:generate
    
    To make it work, we have to define our event and corresponding listener in EventServiceProvider.php. So for test purpose lets provide following values in $listen variable.
    'App\Events\DeleteBranchCourse' => [
                'App\Listeners\DeleteCourseConfirmation',
            ], 
    
    Now we are ready to run our command
    php artisan event:generate
    
    So if we look carefully to Events and Listeners folders, we can see, DeleteBranchCourse and DeleteCourseConfirmation class created respectively. So to make listeners queue , we have to implement ShouldQueue and to manually configure queued jobs, we have to use InteractsWithQueue traits.
    class DeleteCourseConfirmation implements ShouldQueue(){
      use InteractsWithQueue; 
    }
    So to use queue , we have to use database as queue driver. Now we will create a function hello in DeleteBranchCourse Event class and call this function from DeleteCourseConfirmation's handler function
    public function handle(DeleteBranchCourse $event)
        {
    
            $this->attempts($event->hello());
        }
    
    Now we have to fire our event from a controller's function
    Event::fire(new DeleteBranchCourse($feeId));

    Create Your own command on Laravel 5.2


    In Laravel application , when you try this command
     php artisan
    you would see lots of command for laravel application. So if you want to create your own command, laravel provide you very easy way to do this. Here is the command you need.
     php artisan make:console
    To use this command you have to provide a name for the class and you can also provide the name of the command that you want to use in command prompt. So here is the command to make a new command called log:demo
    php artisan make:console LogDemo --command=log:demo
    By running this command, laravel will create a class called LogDemo.class in app/console/commands directory. You can see that there is a protected variable called signature.  
     protected $signature = 'log:demo';
    Here log:demo is the command that you will use on terminal Change the value of description variable as you like. Find handle function and add following line.
    public function handle()
        {
            Log::info('i was here '.Carbon::now());
        }
    
    When you run log:demo command, handle function will be executed. Here this line
    Log::info('i was here '.Carbon::now());
    Will create a line with current time on log file. Which is located on storage/logs directory. Now go to the app/console/kernal.php file. Add this
    'App\Console\Commands\LogDemo',
    string on commands variable. Finally execute php artisan log:demo and this will create a new string on log file. So every time you executed this command, new line will be added on log file.

    Wednesday, August 10, 2016

    Add Cron jobs to run scheduling jobs for Laravel Developer on Ubuntu

    I have faced a lot of problems to run schedule jobs in Laravel.

    I am using Ubuntu 14.04 and i spent a lot of time to make it work.

    Here i wrote down the basic procedure that i followed.

    First 

    To run scheduled jobs first you have to create a new command. To make a command go to your project directory and run following code in terminal:

     
    php artisan make:console Hello

    If you go to app/Console/Commands directory you'll see a new Hello.php class created.

    Now change the signature variable and give a name of your newly created command

    protected $signature = 'Hello';
    Now change the description of the command if you like.

    Now go to app/Console/kernal.php and update commands variable

    protected $commands = [
        Hello::class,];
    Don't forget to add namespace for Hello.php clas.
    Now in handle function we want to do what ever we want. In this example we want to return 'Hi Rashed';

    public function handle(){
    Log::info('i was here ');}
    and add use Log; at the of the Hello.php
    Now Add following code in schedule function on kernal.php file.
    protected function schedule(Schedule $schedule){    $schedule->command('Hello')->everyMinute();}
    So you can see i am trying to run Hello command in every minutes.
    Now Everything is ready and all we have to do is setting up a cron for this project.

    To do so, open a terminal and type

    corntab -e

    Now add following line :

    * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
    Now Run your Project and check storage/logs/laravel.log file to see message.

    Tuesday, August 9, 2016

    Export Excel files in CSV format with UTF-8 encoding in Laravel

    Case : You are given  2 dates ($dateFrom , $dateTo) and you have to find data within given range and export this data in csv format which can encode utf-8 character set.

    We can divide this whole process in 2 parts.

    First( Get Data)

    $first_date = date('Y-m-d 00:00:00', strtotime($dateFrom));
    $last_date  = date('Y-m-d 23:59:59', strtotime($dateTo));
    Now get data from database: 
    $admission_details_all=$this->getCompletedReportResult($first_date,$last_date);
    Second(Export To Csv)
     First we have to define , which field we want to show in csv file.

    So declare fields in an array as follow :

    $arrColumns = array('name', 'phone_no', 'branch_name', 'course_name');

    and remember this fields represents the field name you'll query from database.

    The define first row of the csv file:

    $arrFirstRow = array('Name', 'Phone No', 'Branch', 'Course');
    $options = array(    'columns' => $arrColumns,    'firstRow' => $arrFirstRow,);
    now create a function convertToCSV($admission_details_all, $options, $dateFrom ,$reportType) 
    $admission_details_all is the data we get from database
    $options is an array which has $arrColumns and $arrFirstRow
    $dateFrom is a date time required to track when you exported your file
    $reportType is required to name the exported file
    now we have to call  convertToCSV function and return it.
    return $csvconversionrepo->convertToCSV($admission_details_all, $options, $dateFrom ,$reportType); 
    Here is the screen shot of  convertToCSV funtion