Saturday, May 28, 2016

Laravel 5 : How to check current URL or Route

Hi

Today we will learn how to check or get current url or route.

Sometimes we need to check current URL or route and do some action.

1. Check if URL = myurl

Simply – we need to check if URL is exactly like myurl and then we show something.

In Controller:

if (\Request::is('myurl')) {
  // do some thing
}

In Blade file – almost identical:

@if (\Request::is('companies'))
  // do some thing
@endif


2. Check if URL contains myurl

A little more complicated example – method Request::is() allows a pattern parameter, like this:


if (\Request::is('myurl/*')) {
  // will match URL /myurl/999 or /myurl/create
}


3. Check route by its name

As we know, every route can be assigned to a name, in routes.php file it looks something like this:

Route::get('/myroute', ['as' => 'myrt', function () {
  return view('myroute');
}]);

So we can check if current route is myrt

if (\Route::current()->getName() == 'myrt') {
  // We are on a correct route!
}

So these are three ways to check current URL or route.

Thanks

Friday, May 20, 2016

Laravel 5 Validation rules "sometimes"

Hi

Today we will discuss validation rules "sometimes", apply rules only if field exists.

Imagine that we have two forms – one with username/password fields and another with email/password fields. And we want to have the same validation rules (either in Request, or directly in Controller, doesn’t matter).

And we need to validate if the email is filled in ONLY if that field is present within the form. Then we call it ‘sometimes’.

$this->validate($request, [
  'email' => 'sometimes|required|email'
]);

To understand better, Let’s look at the difference between this code and the “simple” one:

$this->validate($request, [
  'email' => 'required|email'
]);

The second validation will fail if the email field is empty or is not in the form at all. That’s the key point – the first validation will fail only when the field is present but empty.

It is simple but I hope that it will help someone.

Thanks

Friday, May 6, 2016

How to Log every request & response in Laravel 5

Hello Everyone,

Today we will discuss about how to log every request & response in Laravel 5.1.

Sometimes it's useful to log some/all requests to our application. This is really convenient when we use Laravel to build our APIs.

A logging middleware might log all incoming requests to our application. In Laravel 5.1 there is a terminate method and it's call after the sending HTTP response to the browser. This way we have access to both $request and $response at the same time.

Let's take a look at how we are going to achieve this in Laravel 5.1:

Create a new middleware by typing this command in terminal inside our project directory.

php artisan make:middleware LogAfterRequest

And then put below code in it(project_dir/app/Http/Middleware/LogAfterRequest.php).

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogAfterRequest {

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::info('app.requests', ['request' => $request->all(), 'response' => $response]);
    }

}

In this code terminate method receives $request and $response. These are objects which will give us all of the handy stuffs we probably need to log.

When we have our middleware ready, we should add it to our HTTP Kernel.

Open Kernel.php and add this line to our protected $middleware property:

\App\Http\Middleware\LogAfterRequest::class

That's it. We can additionally filter what we want to actually log, but this is the basics.

Thanks.

Friday, April 29, 2016

Conditionally Loading Service Providers in Laravel 5

Hello Everybody,

Today we will discuss about conditionally Loading Service Providers in Laravel 5.1

Since Laravel 5 flattened a lot of the environment-specific structures, much of the configuration that was once stored in different config directories for each environment has now moved into .env files.

But one that can't just live in .env is the environment-dependent loading of service providers.

On a project we're working on, we want to register our error handlers in service providers, and we want to register a different error handler depending on the environment. We have two: ProductionErrorHandler and VerboseErrorHandler, the second of which is for development environments.

Loading service providers normally
In case you're not familiar, defining normal (non-environment-specific) Service Providers happens in /config/app.php. There's a providers array there that looks a bit like this:

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        'Illuminate\Foundation\Providers\ArtisanServiceProvider',
        'Illuminate\Auth\AuthServiceProvider',
        'Illuminate\Bus\BusServiceProvider',
        ...
    ]

So, if your service provider should be loaded in every environment, just toss it into that array and you're good to go.

Loading service providers conditionally
However, if you want to make it conditional, you'll need to head over to /app/Providers/AppServiceProvider.php. This file is the general place you're going to want to be booting and registering anything that's not handled in another service provider, so this is a place you can go to conditionally register your service providers.

Here's what it looks like right now:

<?php namespace app\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * This service provider is a great spot to register your various container
     * bindings with the application. As you can see, we are registering our
     * "Registrar" implementation here. You can add your own bindings too!
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );
    }
}

So, let's do our switch.

    // AppServiceProvider.php

    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );

        if ($this->app->environment('production')) {
            $this->app->register('App\Providers\ProductionErrorHandlerServiceProvider');
        } else {
            $this->app->register('App\Providers\VerboseErrorHandlerServiceProvider');
        }
    }
$this->app->register() will set up the service provider just like adding it to config/app.php will, so its register() and boot() methods will get called at the appropriate times.

We could also use switch instead of if, or we could do your work based on other environment variables, or whatever else--but this is our current best bet to conditionally load service providers. 

Friday, April 8, 2016

How to create and apply a patch with Git

Hi, Today we will learn how to create and apply a patch with Git.

To make creating patches easier, there are some common git practices we should follow. It’s not necessary, but it will make our life easier.

If you fix a bug or create a new feature – we should do it in a separate branch!

Let’s say we want to create a patch for my branch branch1. We clone repository and create a new branch for the fix we have in mind. In this sample we’ll do an imaginary fix for branch2.

git clone git://github.com/username/branch1.git
cd branch1
git checkout -b branch2

Now, in the new branch2 branch we can hack whatever we need to fix. Write tests, update code etc. etc.

When we’re satisfied with all our changes, it’s time to create our patch.

Creating the patch
Okay, We’ve made some commits, in branch2 branch:

Okay, now it’s time to go and make a patch! All we really want are the two latest commits, stuff them in a file and apply them. But, since we created a separate branch, we don’t have to worry about commits at all!

git format-patch master --stdout > branch2_patch.patch

This will create a new file branch2_patch.patch with all changes from the current (branch2) against master. Normally, git would create a separate patch file for each commit, but that’s not what we want. All we need is a single patch file.

Now, you have a patch for the fix we wrote.

Applying the patch

First, take a look at what changes are in the patch. We can do this easily with git apply

git apply --stat branch2_patch.patch

Note that this command does not apply the patch, but only shows us the stats about what it’ll do. After peeking into the patch file with our favorite editor, we can see what the actual changes are.

Next, we’re interested in how troublesome the patch is going to be. Git allows us to test the patch before we actually apply it.

git apply --check branch2_patch.patch

If we don’t get any errors, the patch can be applied cleanly. Otherwise we may see what trouble we’ll run into. To apply the patch, We’ll use git am instead of git apply. The reason for this is that git am allows us to sign off an applied patch. This may be useful for later reference.

git am --signoff < branch2_patch.patch

Okay, patches were applied cleanly and our master branch has been updated.

In our git log, we’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.

Thanks.

Friday, April 1, 2016

Passing parameters to Middleware in Laravel 5.1

Middleware is like a decorator that goes around our entire application request. It takes in a request, does some work, and spits out a response. And usually, it does that work consistently across every section of our application.

But what if we want to be able to customize exactly how the middleware is being processed for a given route, without creating a new middleware for every place it's customized?

Let's consider the most common example: Scoping authentication middleware based on roles. You want to, in the route definition, choose how the authentication middleware runs, by passing it a "role" parameter that defines which user role is required in order to access this route.

Using parameterized middleware in the route defintion #
When we are adding middleware to a route definition, we would normally set it like this:

Route::get('company', ['middleware' => 'auth', function () {
    return view('company.admin');
}]);

So, let's add in our parameter to show that the user must have the owner role:

Route::get('company', ['middleware' => 'auth:owner', function () {
    return view('company.admin');
}]);

Note that we can also pass multiple parameters as a comma-separated list:

Route::get('company', ['middleware' => 'auth:owner,view', function () {
    return view('company.admin');
}]);
Creating parameterized middleware #
So, how do we update our middleware to teach it to take parameters?

<?php

namespace App\Http\Middleware;

use Closure;

class Authentication
{
    public function handle($request, Closure $next, $role)
    {
        if (auth()->check() && auth()->user()->hasRole($role)) {
            return $next($request);
        }

        return redirect('login');
    }
}

Note that the handle() method, which usually only takes a $request and a $next closure, has a third parameter, which is our middleware parameter. If we passed in multiple parameters to our middleware call in the route definition, we can add more parameters to our handle() method:

public function handle($request, Closure $next, $role, $action)

We need to ensure that this middleware is registered in the HTTP Kernel as a routeMiddleware—there's no way we could pass parameters to a universal middleware.

Friday, March 18, 2016

How to implement quickbooks online api in laravel 5.2

Hi, Today we will learn how to integrate quickbooks online in laravel 5.2.

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 app/config/app.php.

require_once '../QuickBooks.php';

In your .env file add the following configuration value:

QUICKBOOK_TOKEN = 95555248baf11b43fbb944ab97de9134ad85
QBO_OAUTH_CONSUMER_KEY = your consumer key
QBO_CONSUMER_SECRET = your consumer secret
QBO_SANDBOX = true
QBO_OAUTH_URL = http://yourdomain.com/qbo/oauth
QBO_SUCCESS_URL = http://yourdomain.com/qbo/success
QBO_MENU_URL = http://yourdomain.com/docs/partner_platform/example_app_ipp_v3/menu.php
QBO_DSN = mysqli://username:password@localhost/yourdbname
QBO_ENCRYPTION_KEY = bcde1234
QBO_USERNAME = DO_NOT_CHANGE_ME
QBO_TENANT = 12345

Now make a controller in app/Http/Controllers

QuickBookController.php.

Write following code to your controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class QuickBookController extends Controller
{

    private $IntuitAnywhere;
    private $context;
    private $realm;

    public function __construct(){
        if (!\QuickBooks_Utilities::initialized(env('QBO_DSN'))) {
            // Initialize creates the neccessary database schema for queueing up requests and logging
            \QuickBooks_Utilities::initialize(env('QBO_DSN'));
        }
        $this->IntuitAnywhere = new \QuickBooks_IPP_IntuitAnywhere(env('QBO_DSN'), env('QBO_ENCRYPTION_KEY'), env('QBO_OAUTH_CONSUMER_KEY'), env('QBO_CONSUMER_SECRET'), env('QBO_OAUTH_URL'), env('QBO_SUCCESS_URL'));
    }
    public function  qboConnect(){


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

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

            return true;
        } else {
            return false;
        }
    }

    public function qboOauth(){
        if ($this->IntuitAnywhere->handle(env('QBO_USERNAME'), env('QBO_TENANT')))
        {
            ; // The user has been connected, and will be redirected to QBO_SUCCESS_URL automatically.
        }
        else
        {
            // If this happens, something went wrong with the OAuth handshake
            die('Oh no, something bad happened: ' . $this->IntuitAnywhere->errorNumber() . ': ' . $this->IntuitAnywhere->errorMessage());
        }
    }

    public function qboSuccess(){
        return view('qbo_success');
    }

    public function qboDisconnect(){
        $this->IntuitAnywhere->disconnect(env('QBO_USERNAME'), env('QBO_TENANT'),true);
        return redirect()->intended("/yourpath");// afer disconnect redirect where you want

    }

    public function createCustomer(){

        $CustomerService = new \QuickBooks_IPP_Service_Customer();

        $Customer = new \QuickBooks_IPP_Object_Customer();
        $Customer->setTitle('Ms');
$Customer->setGivenName('Shannon');
$Customer->setMiddleName('B');
$Customer->setFamilyName('Palmer');
$Customer->setDisplayName('Shannon B Palmer ' . mt_rand(0, 1000));
        // Terms (e.g. Net 30, etc.)
        $Customer->setSalesTermRef(4);

        // Phone #
        $PrimaryPhone = new \QuickBooks_IPP_Object_PrimaryPhone();
        $PrimaryPhone->setFreeFormNumber('860-532-0089');
$Customer->setPrimaryPhone($PrimaryPhone);

        // Mobile #
        $Mobile = new \QuickBooks_IPP_Object_Mobile();
        $Mobile->setFreeFormNumber('860-532-0089');
$Customer->setMobile($Mobile);

        // Fax #
        $Fax = new \QuickBooks_IPP_Object_Fax();
        $Fax->setFreeFormNumber('860-532-0089');
$Customer->setFax($Fax);

        // Bill address
        $BillAddr = new \QuickBooks_IPP_Object_BillAddr();
        $BillAddr->setLine1('72 E Blue Grass Road');
$BillAddr->setLine2('Suite D');
$BillAddr->setCity('Mt Pleasant');
$BillAddr->setCountrySubDivisionCode('MI');
$BillAddr->setPostalCode('48858');
$Customer->setBillAddr($BillAddr);

        // Email
        $PrimaryEmailAddr = new \QuickBooks_IPP_Object_PrimaryEmailAddr();
        $PrimaryEmailAddr->setAddress('support@consolibyte.com');
        $Customer->setPrimaryEmailAddr($PrimaryEmailAddr);

        if ($resp = $CustomerService->add($this->context, $this->realm, $Customer))
        {
            //print('Our new customer ID is: [' . $resp . '] (name "' . $Customer->getDisplayName() . '")');
            //return $resp;
            //echo $resp;exit;
            //$resp = str_replace('{','',$resp);
            //$resp = str_replace('}','',$resp);
            //$resp = abs($resp);
            return $this->getId($resp);
        }
        else
        {
            //echo 'Not Added qbo';
            print($CustomerService->lastError($this->context));
        }
    }

    public function addItem(){
        $ItemService = new \QuickBooks_IPP_Service_Item();

        $Item = new \QuickBooks_IPP_Object_Item();

        $Item->setName('My Item');
$Item->setType('Inventory');
$Item->setIncomeAccountRef('53');

        if ($resp = $ItemService->add($this->context, $this->realm, $Item))
        {
            return $this->getId($resp);
        }
        else
        {
            print($ItemService->lastError($this->context));
        }
    }

    public function addInvoice($invoiceArray,$itemArray,$customerRef){

        $InvoiceService = new \QuickBooks_IPP_Service_Invoice();

        $Invoice = new \QuickBooks_IPP_Object_Invoice();

        $Invoice = new QuickBooks_IPP_Object_Invoice();

$Invoice->setDocNumber('WEB' . mt_rand(0, 10000));
$Invoice->setTxnDate('2013-10-11');

$Line = new QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount(12.95 * 2);
$Line->setDescription('Test description goes here.');

$SalesItemLineDetail = new QuickBooks_IPP_Object_SalesItemLineDetail();
$SalesItemLineDetail->setItemRef('8');
$SalesItemLineDetail->setUnitPrice(12.95);
$SalesItemLineDetail->setQty(2);

$Line->addSalesItemLineDetail($SalesItemLineDetail);

$Invoice->addLine($Line);

$Invoice->setCustomerRef('67');


        if ($resp = $InvoiceService->add($this->context, $this->realm, $Invoice))
        {
            return $this->getId($resp);
        }
        else
        {
            print($InvoiceService->lastError());
        }
    }

    public function getId($resp){
        $resp = str_replace('{','',$resp);
        $resp = str_replace('}','',$resp);
        $resp = abs($resp);
        return $resp;
    }  

}

Now in app/Http/routes.php, add the following route

Route::get('qbo/oauth','QuickBookController@qboOauth');
Route::get('qbo/success','QuickBookController@qboSuccess');
Route::get('qbo/disconnect','QuickBookController@qboDisconnect');

Now in a page, where you want to show quickbook connect button, add the following code in header section, In mine case, I have added in app.blade.php

<script type="text/javascript" src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere.js"></script>
<script type="text/javascript">
intuit.ipp.anywhere.setup({
menuProxy: '<?php print(env('QBO_MENU_URL')); ?>',
grantUrl: '<?php print(env('QBO_OAUTH_URL')); ?>'
});
</script>

In body of that page include the following line of code
<?php
$qbo_obj = new \App\Http\Controllers\QuickBookController();
$qbo_connect = $qbo_obj->qboConnect();
?>
@if(!$qbo_connect)
<ipp:connectToIntuit></ipp:connectToIntuit>
@else
<a href="{{url('qbo/disconnect')}}" title="">Disconnect</a>
@endif

Make a blade page for success, in resources/views/qbo_success.blade.php, and add the following line of code:

<html>
<head>
    <title>Test</title>
</head>
<body>

<div style="text-align: center; font-family: sans-serif; font-weight: bold;">
    You're connected! Please wait...
</div>

<script type="text/javascript">
    window.opener.location.reload(false);
    window.setTimeout('window.close()', 2000);
</script>

</body>
</html>

I have made 3 function in a above given controller to show how to add item, customer and invoices.

createCustomer - for adding customer to quickbook
addItem - For adding item to quickbook
addInvoice - for adding invoices

Hope it will help you.

Thanks