Friday, February 12, 2016

Laravel : How to make migration for change data type

Hi,

Today, we will learn how to make migration for change the data type of a column.

I needed to change the type of a column from VARCHAR to TEXT.

First on your terminal write the following comman to make migration file:

php artisan make:migration change_data_type_of_column_in_tablename

This will create a new file named date_change_data_type_of_column_in_tablename.php in database/migrations folder.

Open this file in your editor and write the following script as given.

public function up()
{
    DB::statement('ALTER TABLE tablename MODIFY COLUMN columnname TEXT');
}

public function down()
{
    DB::statement('ALTER TABLE tablename MODIFY COLUMN columnname VARCHAR(255)');
}

Then on your terminal run the command : php artisan migrate

This will change the given column data type.

Thanks

Friday, February 5, 2016

How to implement Breadcrumbs in Laravel 5.1

 Hi, today we will discuss about how to implement Breadcrumbs in Laravel 5.1.


1. Install Laravel Breadcrumbs


Note:-Laravel 5.0 or above is required – use the 2.x version for Laravel 4.


Install with Composer

Run this at the command line:

$ composer require davejamesmiller/laravel-breadcrumbs

This will both update composer.json and install the package into the vendor/ directory.

Add to config/app.php

Add the service provider to providers:

'providers' => [
    // ...
    DaveJamesMiller\Breadcrumbs\ServiceProvider::class,
],

And add the facade to aliases:

'aliases' => [
    // ...
    'Breadcrumbs' => DaveJamesMiller\Breadcrumbs\Facade::class,
],

2. Define your breadcrumbs


Create a file called app/Http/breadcrumbs.php that looks like this:

<?php

// Home
Breadcrumbs::register('home', function($breadcrumbs)
{
    $breadcrumbs->push('Home', route('home'));
});

// Home > About
Breadcrumbs::register('about', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('About', route('about'));
});

// Home > Blog
Breadcrumbs::register('blog', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('Blog', route('blog'));
});

// Home > Blog > [Category]
Breadcrumbs::register('category', function($breadcrumbs, $category)
{
    $breadcrumbs->parent('blog');
    $breadcrumbs->push($category->title, route('category', $category->id));
});

// Home > Blog > [Category] > [Page]
Breadcrumbs::register('page', function($breadcrumbs, $page)
{
    $breadcrumbs->parent('category', $page->category);
    $breadcrumbs->push($page->title, route('page', $page->id));
});

3. Choose a template


By default a Bootstrap-compatible ordered list will be rendered, so if you’re using Bootstrap 3 you can skip this step.

First initialise the config file by running this command:

$ php artisan vendor:publish

Then open config/breadcrumbs.php and edit this line:

'view' => 'breadcrumbs::bootstrap3',

The possible values are:

    Bootstrap 3: breadcrumbs::bootstrap3
    Bootstrap 2: breadcrumbs::bootstrap2
    The path to a custom view: e.g. _partials/breadcrumbs

4. Output the breadcrumbs


Finally, call Breadcrumbs::render() in the view template for each page, passing it the name of the breadcrumb to use and any additional parameters – for example:

{!! Breadcrumbs::render('home') !!}

{!! Breadcrumbs::render('category', $category) !!}

Friday, January 22, 2016

Add extra column in migration after creating a table in Laravel 5.2

Hello Everyone,

Today, we will discuss about how to add an extra column in migration after creating a table.

First time we create a table's migration & execute migration command. After this , we realize that we have to add a new column in table.

For this, we can modify table by this easy way.

Firstly run this command for create a new migration file.

php artisan make:migration add_column_name_in_users_table

It will create a new file in migration file. Write in its up() function the following lines.

 Schema::table('users', function ($table) {
            $table->string('column_name');
          });


and in down() function write the following lines:

Schema::table('users', function ($table) {
            $table->drop_column('
column_name');

          });

Make sure you put the same table name which you want to edit.

Now run migration command for this file.

php artisan migrate

Thanks.

Friday, January 15, 2016

Defining middleware in laravel

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering our application. For example, Laravel includes a middleware that verifies the user of our application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/Middleware directory.


Defining Middleware

To create a new middleware, use the make:middleware Artisan command:

php artisan make:middleware OldMiddleware

This command will place a new OldMiddleware class within our app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 20. Otherwise, we will redirect the users back to the "home" URI.

<?php

namespace App\Http\Middleware;

use Closure;

class OldMiddleware
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->input('age') <= 20) {
            return redirect('home');
        }

        return $next($request);
    }

}
As we can see, if the given age is less than or equal to 20, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the $next callback with the $request.

It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit our application. Each layer can examine the request and even reject it entirely.

Before / After Middleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}
However, this middleware would perform its task after the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}

Friday, January 8, 2016

How to implement quickbooks online in laravel 5.1

Hi, Today we will learn how to integrate quickbooks online in laravel 5.1.
The very first thing we'll have to do is register our app with Intuit. When we do this, Intuit will give us these variables:
  • app token
  • consumer secret
  • consumer key

 The installation

Add this to your composer.json.
"require": {    
    "consolibyte/quickbooks": "^3.1"   
},

This will give us a page in root folder, QuickBooks.php. Include this page in public/index.php.

require_once '../QuickBooks.php';

Now make a controller in app/Http/Controllers

QuickBookController.php.

Write following code to your controller:

class QuickBookController extends Controller
{
    public function __Construct()
    {
        $oauth_consumer_key = 'your consumer key';
        $oauth_consumer_secret = 'consumer secret';
        $sandbox = true;     // When you're using development tokens
        $dsn = 'mysqli://root:root@localhost/DbName';
        $encryption_key = 'encryption key';
        $the_username = 'DO_NOT_CHANGE_ME';
        $the_tenant = 12345;

        if (!\QuickBooks_Utilities::initialized($dsn)) {
            // Initialize creates the neccessary database schema for queueing up requests and logging
            \QuickBooks_Utilities::initialize($dsn);
        }
        $IntuitAnywhere = new \QuickBooks_IPP_IntuitAnywhere($dsn, $encryption_key, $oauth_consumer_key, $oauth_consumer_secret, '', '');

        if ($IntuitAnywhere->check($the_username, $the_tenant) && $IntuitAnywhere->test($the_username, $the_tenant)) {
            // Set up the IPP instance
            $IPP = new \QuickBooks_IPP($dsn);
            // Get our OAuth credentials from the database
            $creds = $IntuitAnywhere->load($the_username, $the_tenant);
            // Tell the framework to load some data from the OAuth store
            $IPP->authMode(
                \QuickBooks_IPP::AUTHMODE_OAUTH,
                $the_username,
                $creds);

            if ($sandbox) {
                // Turn on sandbox mode/URLs
                $IPP->sandbox(true);
            }
            // This is our current realm
            $this->realmId = $creds['qb_realm'];
            // Load the OAuth information from the database
            $this->context = $IPP->context();
        } else {
            return false;
        }
    }

    public function getCustomerCount()
    {
        //echo csrf_token();
        $VendorService = new \QuickBooks_IPP_Service_Vendor();

        $vendors = $VendorService->query($this->context, $this->realmId, "SELECT * FROM Customer");
        print_r($vendors);
        exit;
        foreach ($vendors as $Vendor) {
            print('Vendor Id=' . $Vendor->getId() . ' is named: ' . $Vendor->getDisplayName() . '<br>');
        }
    }


}

The constructer will give connection to quickbook online account. After that you can make function to your use like getCustomerCount().


Friday, December 25, 2015

.htaccess Tips and Tricks for WordPress

The .htaccess file is a configuration file that helps us to control files and folders in the current directory, and all other sub-directories. The filename .htaccess stands for hypertext access and is supported by most servers.

Many WordPress users make use of .htaccess file when they customize their website’s permalink settings. However we can do so much more. The .htaccess file is a powerful configuration file that allows us to enhance our site’s security and performance. In this article, we will show 9 most powerful .htaccess tricks for WordPress that we can try on our site right away.
Before we start making any change, we need to backup our current .htaccess file) in a cloud storage service like Dropbox or Connect to your website using an FTP client and simply download the .htaccess file to your computer. So that, if something goes wrong, then we can upload the backup file.
If you are not able to access .htaccess file, then make sure your FTP client is set to show hidden files. If you do not have an .htaccess file in your website’s root folder, then you have to create one. Simply create a blank text file and save it as .htaccess. Make sure to name file as .htaccess and not htaccess. Lastly, you need to upload the file to your website’s root folder.

1.     Secure Your WordPress Admin Area

Admin Area Password PRotection
The wp-admin folder contains the files required to run the WordPress dashboard. In most cases, your users don’t need access to the WordPress dashboard, unless they want to register an account. A powerful security measure is to enable only a few selected IP addresses to access the wp-admin folder. You can use .htaccess to secure your WordPress admin area by limiting the access to selected IP addresses only. Simply copy and paste following code into your .htaccess file:
# Limit logins and admin by IP
<Limit GET POST PUT>
order deny,allow
deny from all
allow from x.xx.xx.xx
allow from IP_ADDRESS_2
</Limit>
Replace x.xx.xx.xx with your own IP addresses. If you are using more than one IP address to access the internet, then make sure you add them as well.

2.     Protect Your WordPress Configuration wp-config.php File from everyone

Probably the most sensitive file in your WordPress website’s root directory is wp-config.php file, which contains the database name and access credentials and various other critical data and how to connect to it. And of course, you want to disable public access to the source of all this security – the .htaccess file itself. To protect your wp-config.php file from unathorized access, simply add this code to your .htaccess file:
# Deny access to wp-config.php file
<files wp-config.php>
order allow,deny
deny from all

</files>

3.     Deny Image Hotlinking in WordPress Using .htaccess

When someone uses your site’s image, they can steal you bandwidth by hotlinking images from your website and most of the time, you’re not even credited for it. Normally, this doesn’t concern form most users. But, if you run a popular site with lot of images and photos, then hotlinking can become a major issue. You can stop image hotlinking by adding following code in your .htaccess file:
#disable hotlinking of images in WordPress
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?website.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?otherwebsite.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ [NC,R,L]

4.     Disable Directory Browsing in WordPress

Directory Browsing
By default, the Apache web server enables directory browsing. That means all files and folders inside the root of the web server are enlist able and accessible by a visitor. With directory browsing enabled, hackers can get into your site’s directory and file structure to find a vulnerable file.
To disable directory browsing in WordPress using .htaccess all you need to do is add this single line in your .htaccess file:
# Disable directory browsing in WordPress
Options All –Indexes

5.     Allow Only Selected Files from wp-content

As you know the wp-content folder contains the all your themes, plugins and media upload. You defiantly don’t want people to access it without restrictions. In addition to denying directory browsing, you can also disable access of all file types, save a few. On the basis of this, you can selectively unblock files like JPG, DOCX, PDF, CSS, JS, etc. and deny from the rest. To do this, paste following code in your .htaccess file:
# Disable access to all file types except the following
  Order deny,allow
  Deny from all
  <Files ~ “.(xml|css|js|jpe?g|png|pdf|gif|docx|rtf|odf|zip|rar)$”>
  Allow from all
  </Files>

6.     Disable PHP Execution in Some WordPress Directories

Hacked WordPress sites usually have backdoor files sometimes. These backdoor files are often disguised as core WordPress files and are present in /wp-includes/ or /wp-content/uploads/ folders. An simple way to increase your WordPress security is by denying PHP execution for some WordPress directories. To do this, paste following code in a blank .htaccess file:
# Deny PHP Execution to all file
deny from all

</Files>

7.     Protect .htaccess From Unauthorized Access

As you have seen that there are a lot of things that can be done using .htaccess file. Due to the power and control it has on your web server, it is necessary that you also protect it from unauthorized access by hackers. To do this, paste following code in a blank .htaccess file:
# Protect .htaccess From Unauthorized Access
<files ~ “^.*.([Hh][Tt][Aa])”>
order allow,deny
deny from all
satisfy all
</files>
We can, still edit the file ourselves using FTP and through file manager of our hosting control panel.

Friday, December 18, 2015

Wordpress : Creating Tables and additional data with Plugins

Hello to everyone. Today i will show you that how to create table and additional data with plugin in wordpress. So, please follow the steps below to have your plugin automatically create its database tables:
  1. Write a PHP function that creates the table.
  2. Ensure that WordPress calls the function when the plugin is activated.
  3. Create an upgrade function, if a new version of your plugin needs to have a different table structure.
Creating Database Table:
The first step in making your plugin create database tables automatically is to create a PHP function within your plugin that adds a table or tables to the WordPress MySQL database. Lets suppose that we want to create table_for_plugin function.

Database Table Prefix:
In the wp-config.php file, a WordPress site owner can define a database table prefix. By default, the prefix is "wp_", but we'll need to check on the actual value and use it to define your database table name. This value is found in the $wpdb->prefix variable. 

So, if we want to create a table called mypluginconfig, the first few lines of your table-creation function will be:
function  () {
   global $wpdb;

   $table_name = $wpdb->prefix . "mypluginconfig"; 
}
The whole function for creating a table and adding initial data will be :

<?php

function table_for_plugin() {
 global $wpdb;
 global $jal_db_version;

 $table_name = $wpdb->prefix . 'mypluginconfig';
 
 $charset_collate = $wpdb->get_charset_collate();

 $sql = "CREATE TABLE $table_name (
  id mediumint(9) NOT NULL AUTO_INCREMENT,
  time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  name tinytext NOT NULL,
  text text NOT NULL,
  url varchar(55) DEFAULT '' NOT NULL,
  UNIQUE KEY id (id)
 ) $charset_collate;";

 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
 dbDelta( $sql );

 
}

function plugin_install_data() {
 global $wpdb;
 
 $welcome_name = 'Mr. WordPress';
 $welcome_text = 'Congratulations, you just completed the installation!';
 
 $table_name = $wpdb->prefix . 'mypluginconfig';
 
 $wpdb->insert( 
  $table_name, 
  array( 
   'time' => current_time( 'mysql' ), 
   'name' => $welcome_name, 
   'text' => $welcome_text, 
  ) 
 );
}
Calling the function:

Now that we have the initialization function defined, we want to make sure that WordPress calls this function when the plugin is activated by a WordPress administrator. To do that, we will use the activate_ action hook. If our plugin file is wp-content/plugins/plugindir/pluginfile.php, we'll add the following line to the main body of our plugin:
register_activation_hook( __FILE__, 'table_for_plugin' );
register_activation_hook( __FILE__, 'plugin_install_data' );

This is how we add new table and initial data with plugin installation.