Friday 26 February 2016

LARAVEL 5 + GOOGLE APIS CLIENT LIBRARY

Hi Everybody,

Today we will discuss about integration of google api client library with laravel 5.1

Prerequisite

Created a google app project
Enabled Google+ API at your google project
Created new Client ID
Generated API Key
Get service account name

You can find in this google link to do above steps.If you have already done those, you can start the following steps.

Step1


In your composer.json file, add

"require": {
 "google/apiclient": "1.0.*@beta"//This beta version is when I use, get updated version when you use
 }

Step2


(My apiclient version is still beta, so I need to set minimum-stability to dev, but if your version is stable, you don’t need to change and skip to Step3)Find minimum-stability in your laravel project, and change to

"minimum-stability": "dev"

Step3


run >>>>composer update. After that, you will see google folder under yourapp>vendor folder.

Step4


In your composer.json file, add the following;

{ "autoload": 
     { "classmap": [ "vendor/google/apiclient/src/Google" ],
      } 
}

Step5


In your http://console.developers.google.com Create a new Client ID in Credentials, Select Service account and click on Create Client ID

Step6


In config folder, add google.php and add;

return [
    'app_name'          => 'your_app_name', 
    'client_id'         => 'your_client_id',
    'client_secret'     => 'your_client_secret',
    'api_key'           => 'your_api_key',
    'service_account_name' => 'your_service_account_name'
];

Step7


Create app>Services>Google.php file and then add the following code;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;

class Google {

    protected $client;

    protected $service;

    function __construct() {
        /* Get config variables */
        $client_id = Config::get('google.client_id');
        $service_account_name = Config::get('google.service_account_name');
        $key = Config::get('google.api_key');//you can use later

        $this->client = new \Google_Client();
        $this->client->setApplicationName("your_app_name");
        $this->service = new \Google_Service_Books($this->client);//Test with Books Service        
    }

    public function getBooks(){
        $optParams = array('filter' => 'free-ebooks');
        $results = $this->service->volumes->listVolumes('Henry David Thoreau', $optParams);

        dd($results);
    }
}

Step8


In HomeController, modify index function

public function index(Google $google)
{
    $result = $google->getBooks();
    print_r($result);
}


Thanks.

Friday 19 February 2016

Manually Authenticating Users In Laravel 5.1

Hi Everybody,

Today we will discuss about manually authenticating of users in Laravel 5.1

Of course, you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly.

We will access Laravel's authentication services via the Auth facade, so we'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method:

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Routing\Controller;

class AuthController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the hashed password value passed to the method via the array. If the two hashed passwords match an authenticated session will be started for the user.

The attempt method will return true if authentication was successful. Otherwise, false will be returned.

The intended method on the re director will redirect the user to the URL they were attempting to access before being caught by the authentication filter. A fallback URI may be given to this method in case the intended destination is not available.

If you wish, you also may add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as "active":

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session:

Auth::logout();

Note: In these examples, email is not a required option, it is merely used as an example. You should use whatever column name corresponds to a "username" in your database.

Thanks.

Friday 12 February 2016

Delete a file in Laravel 5.1

Hi Everybody,

Today we will discuss how to delete a file in Laravel 5.1

You know you could use PHP's unlink() method, but want to do it the Laravel way then use the File::delete() method.

<?php

namespace App\Http\Controllers;

use File;

class TestController extends Controller
{

public function deleteFile()
{
// Delete a single file
File::delete($filename);

// Delete multiple files
File::delete($file1, $file2, $file3);

// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
}

}
?>

Errors are quietly ignored.

If there's a problem deleting the file, any error is silently ignored. If it's important that a file was deleted, check it's existence after deleting it with File::exists().

Thanks.

Friday 5 February 2016

Easily enable CORS in Laravel 5.1

Hi Everybody,

Today we will discuss about how to enable CORS in laravel 5.1.

CORS stands for Cross-Origin Resource Sharing an is a specification that allow modern browsers to request (and receive) data from a domain other than the one serving the page that made the request.

So you’re building your API using Laravel and when when you try to make a XHR request you see the following message in your browser’s console:


This means your server is not sending back to the client the headers that allow CORS:

1.Access-Control-Allow-Origin
2.Access-Control-Allow-Methods

Using your Terminal, navigate to your project’s root directory and issue the following artisan command:

php artisan make:middleware Cors

Now, using your editor of choice, change the newly created /app/Http/Middleware/Cors.php so it look like this:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

Next update /app/Http/Kernel.php adding the following instruction which will make Laravel aware of your custom middleware:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'cors' => \App\Http\Middleware\Cors::class, // <<< add this line
];

To wrap things up, just use your middleware as you’re used to:

Route::get('breweries', ['middleware' => 'cors', function()
{
    return \Response::json(\App\Brewery::with('beers', 'geocode')->paginate(10), 200);
}]);

And that would be all. Of course there are several other options to consider when enabling CORS but the way to return them to the browser is the same, as shown right above.

Thanks.