Friday 18 March 2016

How to generate random password in Laravel 5.1

Hi Everybody,

Today we will discuss about how to generate random password in Laravel 5.1.

This is a really really short one. I just needed to generate a random password for a user and noticed that Google doesn’t really give a one-line answer, which is really simple.

Firstly, how to generate random string – Laravel has a helper called str_random($length). In terms of saving hashed password to database, we use Hash::make($password).

So the end result for generating 8-symbol length password looks as simple as this:

$hashed_random_password = Hash::make(str_random(8));

Of course, don’t forget:
use Illuminate\Support\Facades\Hash;

Generated password can look like:

JnR390XB
2I2so1Wr
oVNBAic9

And hash is something like:

$2y$10$E1.y.jjmr7ecmMAiwFFQMO6KXn0scLB2hvVBbx8cny.lREZ6xdDMW
$2y$10$pVOI0me9sLPRbyQnxNQrDurSoJScsE6nvu6VVOsMDF8qusH7HUlo2
$2y$10$xVPUPgm1vpUTpZ8jAJE/Xeh7j8G8EFnlQYp27Zjy8qnabqessSc2i

That’s it for now, hope it’s a useful short tip.
Thanks.

Friday 11 March 2016

AND-OR-AND + brackets with Eloquent-Laravel 5.1

Hi Everybody,

Today we will discuss about how to use AND-OR-AND + brackets with Eloquent-Laravel 5.1

Eloquent is a great thing – you can build your query step-by-step and then call get() method. But sometimes it gets a little tricky for more complicated queries – for example, if you have multiple AND-OR conditions and you want to put brackets, how to do it properly?

Wrong way – easy to make mistake

Let’s say we need to filter male customers aged 18+ or female customers aged 65+ (whatever the reason is, it’s just a hypothetical example). Simple MySQL query would look something like this:

.... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65)
Now let’s transform it to Eloquent:

//............
$q->where('gender', 'Male');
$q->orWhere('age', '>=', 18);
$q->where('gender', 'Female');
$q->orWhere('age', '>=', 65);

But wait, if we launch it like that, MySQL query wouldn’t have any brackets and would be launches as this:


....WHERE gender = 'Male' and age >= 18 or gender = 'Female' and age >= 65
Which is wrong order – it would actually be executed in this order:


.....WHERE ((gender = 'Male' and age >= 18) or gender = 'Female') and age >= 65

The worst thing is that it wouldn’t throw any errors. And if you don’t test properly, you wouldn’t even notice that it filtered out wrong results.

Right way – putting “brackets” into Eloquent

What we actually need here is a thing called Advanced Where Clauses – where we can assign a function to a where clause, like this:

//......
$q->where(function ($query) use ($gender, $age) {
    $query->where('gender', $gender)
        ->where('age', '>=',  $age;
})->orWhere(function($query) use ($gender, $age) {
    $query->where('gender',  $gender)
        ->where('age', '>=',  $age);
})

This code will produce SQL query exactly like we need – with brackets in the right places.

Thanks.

Friday 4 March 2016

How to add event in google calendar using Laravel 5.1

Hi Everybody,

Today we will discuss about how to add event in google calendar using Laravel 5.1.

For anyone who would like to use Google API with a service account connection, here is what I have to done in order to make it work :

1- Call the following in command line : composer require google/apiclient

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

3- Next, take the *.p12 file and place it somewhere in your laravel directory (in my case in assets).

4- Next, create a new Gooogle calendar (http://calendar.google.com) with any Google account and share it with your Service Account's Email Address created in step 3 and save it.

5- In the config folder, add a file name google.php, place and modify the following content :

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Client ID
    |--------------------------------------------------------------------------
    |
    | The Client ID can be found in the OAuth Credentials under Service Account
    |
    */
    'client_id' => 'something.apps.googleusercontent.com',

    /*
    |--------------------------------------------------------------------------
    | Service account name
    |--------------------------------------------------------------------------
    |
    | The Service account name is the Email Address that can be found in the
    | OAuth Credentials under Service Account
    |
    */
    'service_account_name' => 'something@developer.gserviceaccount.com',

    /*
    |--------------------------------------------------------------------------
    | Key file location
    |--------------------------------------------------------------------------
    |
    | This is the location of the .p12 file from the Laravel root directory
    |
    */
    'key_file_location' => '/resources/assets/filename.p12',
    'app_name'          => 'Application name',
    'client_secret'     => '3rULDQBNHOYAg0ySYpHW',

    'api_key'           => 'AIzaSyBdk8P_lLwpKQkKOamgnw',
];

6- In your application folder, I have added a file named GoogleCalendar.php in App\Services with the following content :

<?php namespace App\Services;

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

class GoogleCalendar {

    protected $client;

    protected $service;

    function __construct() {
        $client_id = Config::get('google.client_id');
        $service_account_name = Config::get('google.service_account_name');
        $key_file_location = base_path() . Config::get('google.key_file_location');
        $client_secret = Config::get('google.client_secret');
        $key = Config::get('google.api_key');//you can use later

        $this->client = new \Google_Client();
        $this->client->setApplicationName("Application name");
        $this->client->setClientId($client_id);
        $this->client->setClientSecret($client_secret);
        $this->client->setDeveloperKey($key);
        $this->client->setScopes(array('https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly'));
        /* If we have an access token */
        if (Cache::has('service_token')) {
            $this->client->setAccessToken(Cache::get('service_token'));
        }

        $key = file_get_contents($key_file_location);
        $scopes = array('https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly');
        $cred = new \Google_Auth_AssertionCredentials(
            $service_account_name,
            $scopes,
            $key
        );

        $this->client->setAssertionCredentials($cred);
        if ($this->client->getAuth()->isAccessTokenExpired()) {
            $this->client->getAuth()->refreshTokenWithAssertion($cred);
        }
        Cache::forever('service_token', $this->client->getAccessToken());
        $this->service = new \Google_Service_Calendar($this->client);
    }

    public function addEvent()
    {
        $service = new \Google_Service_Calendar($this->client);
        $event = new \Google_Service_Calendar_Event();
        $event->setSummary('Appointment');
        $event->setLocation('Somewhere');
        $start = new \Google_Service_Calendar_EventDateTime();
        $start->setDateTime('2016-02-29T13:00:00+05:30');
        $start->setTimeZone('America/Los_Angeles');
        $event->setStart($start);
        $end = new \Google_Service_Calendar_EventDateTime();
        $end->setDateTime('2016-02-29T14:00:00+05:30');
        $start->setTimeZone('America/Los_Angeles');
        $event->setEnd($end);
        $attendee1 = new \Google_Service_Calendar_EventAttendee();
        $attendee1->setEmail('rahul@headerlabs.com');
        // ...
        $attendees = array($attendee1
            //, ...
        );
        $event->attendees = $attendees;
        $createdEvent = $service->events->insert('primary', $event);
        echo $createdEvent->getId();
    }

}

7- Next add the following where you need to use Google Calendar
use App\Services\GoogleCalendar;
[...]
    public function functionName(GoogleCalendar $calendar)
    {
        $event_id = $calendar->addEvent();
    }


Thanks