Monday 5 September 2016

How to add custom condition for logging in a user for prevent a brute force in Laravel 5.0

Hi Everybody,

Today  we will discuss about how to add custom condition for logging in a user for prevent a brute force in Laravel 5.0

As you know Laravel provide throttle library for loaravel 5.1 and newer version, but for laravel 5.0 there is no prdefined throttle so we need to add a custom throttle.
If a user do login with wrong password, so after x attampt account will be lock for y minutes.
See code for this

Inside AuthController.php

public function authenticate()
    {
        // Set login attempts and login time
        $loginAttempts = 1;

        // If session has login attempts, retrieve attempts 
        // counter and attempts time 
         if (Session::has('loginAttempts')) 
        {
            $loginAttempts = Session::get('loginAttempts');
            $loginAttemptTime = Session::get('loginAttemptTime');

            // If attempts > 3 and time < 10 minutes
            if ($loginAttempts > 3 && (time() - $loginAttemptTime <= 600)
            {
                return redirect()-back()->with('error', 'maximum login
 attempts reached. Try again in a while');
            }
        // If time > 10 minutes, reset attempts counter and time in session
            if (time() - $loginAttemptTime > 600)
            {
                Session::put('loginAttempts', 1)
                Session::put('loginAttemptTime', time());
            }
        }
        else // If no login attempts stored, init login attempts and time
        {
            Session::put('loginAttempts', $loginAttempts);
            Session::put('loginAttemptTime', time())
        }
        // If auth ok, redirect to restricted area
        if (Auth::attempt(['email' => 'someone@example.com']))
        {
            return redirect()->intended('dashboard');
        }
        // Increment login attempts
        Session::put('loginAttempts', $loginAttempts + 1);
    } 
 
Thanks 

Friday 19 August 2016

Solved - fatal: Failed to connect to bitbucket.org port 443: Network is unreachable

Hi Everybody,

Today we will discuss about a little but very critical issue i faced with bitbucket.


When i was working on my project repository i found error "fatal: unable to access 'myrepo' Failed to connect to bitbucket.org port 443: Network is unreachable" few day ago. when i going to just git pull command i found error like as bellow:

fatal: unable to access 'https://hardik@bitbucket.org/hardik/setup_backend.git/':
Failed to connect to bitbucket.org port 443: Network is unreachable

But i try to solve it but nothing, at last i found solution i was use HTTPS for clone repo. But i need use SSH for git repo. So i changed remote HTTPS into ssh like as bellow:

git remote -v
git remote remove origin
git remote add origin git@bitbucket.org:hardik/setup_backend.git

And then i try to push and pull, it works, you can also try.

Thanks.

Friday 22 July 2016

How To Install Solr 5.2.1 on Ubuntu 14.04

Hi everybody,

Today we will discuss about how to install apache solr(5.2.1) on Ubuntu 14.04

Solr is a search engine platform based on Apache Lucene. It is written in Java and uses the Lucene library to implement indexing. It can be accessed using a variety of REST APIs, including XML and JSON. This is the feature list from their website:

    Advanced Full-Text Search Capabilities

    Optimized for High Volume Web Traffic

    Standards Based Open Interfaces - XML, JSON and HTTP

    Comprehensive HTML Administration Interfaces

    Server statistics exposed over JMX for monitoring

    Linearly scalable, auto index replication, auto failover and recovery

    Near Real-time indexing

    Flexible and Adaptable with XML configuration

    Extensible Plugin Architecture


In this article, we will install Solr using its binary distribution.

Prerequisites


To follow this tutorial, you will need:

    One 1 GB Ubuntu 14.04 Droplet at minimum, but the amount of RAM needed depends highly on your specific situation.


    A sudo non-root user.


Step 1 — Installing Java


Solr requires Java, so in this step, we will install it.

The complete Java installation process is thoroughly described in this article, but we'll use a slightly different process.

First, use apt-get to install python-software-properties:

    sudo apt-get install python-software-properties

Instead of using the default-jdk or default-jre packages, we'll install the latest version of Java 8. To do this, add the unofficial Java installer repository:

    sudo add-apt-repository ppa:webupd8team/java
You will need to press ENTER to accept adding the repository to your index.

Then, update the source list:

    sudo apt-get update


Last, install Java 8 using apt-get. You will need to agree to the Oracle Binary Code License Agreement for the Java SE Platform Products and JavaFX.

    sudo apt-get install oracle-java8-installer

Step 2 — Installing Solr


In this section, we will install Solr 5.2.1. We will begin by downloading the Solr distribution.

First, find a suitable mirror on this page. Then, copy the link of solr-5.2.1.tgz from the mirror. For example, we'll use http://apache.mirror1.spango.com/lucene/solr/5.2.1/.

Then, download the file in your home directory:

    cd ~
    wget http://apache.mirror1.spango.com/lucene/solr/5.2.1/solr-5.2.1.tgz

Next, extract the service installation file:

    tar xzf solr-5.2.1.tgz solr-5.2.1/bin/install_solr_service.sh --strip-components=2

And install Solr as a service using the script:

    sudo bash ./install_solr_service.sh solr-5.2.1.tgz
Finally, check if the server is running:

    sudo service solr status


You should see an output that begins with this:

Solr status output


Found 1 Solr nodes:

Solr process 2750 running on port 8983

. . .

Step 3 — Creating a Collection


In this section, we will create a simple Solr collection.

Solr can have multiple collections, but for this example, we will only use one. To create a new collection, use the following command. We run it as the Solr user in this case to avoid any permissions errors.

    sudo su - solr -c "/opt/solr/bin/solr create -c gettingstarted -n data_driven_schema_configs"
In this command, gettingstarted is the name of the collection and -n specifies the configset. There are 3 config sets supplied by Solr by default; in this case, we have used one that is schemaless, which means that any field can be supplied, with any name, and the type will be guessed.

You have now added the collection and can start adding data. The default schema has only one required field: id. It has no other default fields, only dynamic fields. If you want to have a look at the schema, where everything is explained clearly, have a look at the file /opt/solr/server/solr/gettingstarted/conf/schema.xml.

Step 4 — Adding and Querying Documents


In this section, we will explore the Solr web interface and add some documents to our collection.

When you visit http://your_server_ip:8983/solr using your web browser, the Solr web interface should appear:

Solr Web Interface


The web interface contains a lot of useful information which can be used to debug any problems you encounter during use.

Collections are divided up into cores, which is why there are a lot of references to cores in the web interface. Right now, the collection gettingstarted only contains one core, named gettingstarted. At the left-hand side, the Core Selector pull down menu is visible, in which you'll be able to select gettingstarted to view more information.

After you've selected the gettingstarted core, select Documents. Documents store the real data that will be searchable by Solr. Because we have used a schemaless configuration, we can use any field. Let'sl add a single document with the following example JSON representation by copying the below into the Document(s) field:

{
    "number": 1,
    "president": "George Washington",
    "birth_year": 1732,
    "death_year": 1799,
    "took_office": "1789-04-30",
    "left_office": "1797-03-04",
    "party": "No Party"
}


Click Submit document to add the document to the index. After a few moments, you will see the following:
Output after adding Document

Status: success
Response:
{
  "responseHeader": {
    "status": 0,
    "QTime": 509
  }
}
You can add more documents, with a similar or a completely different structure, but you can also continue with just one document.

Now, select Query on the left to query the document we just added. With the default values in this screen, after clicking on Execute Query, you will see 10 documents at most, depending on how many you added:
Query output

{
  "responseHeader": {
    "status": 0,
    "QTime": 58,
    "params": {
      "q": "*:*",
      "indent": "true",
      "wt": "json",
      "_": "1436827539345"
    }
  },
  "response": {
    "numFound": 1,
    "start": 0,
    "docs": [
      {
        "number": [
          1
        ],
        "president": [
          "George Washington"
        ],
        "birth_year": [
          1732
        ],
        "death_year": [
          1799
        ],
        "took_office": [
          "1789-04-30T00:00:00Z"
        ],
        "left_office": [
          "1797-03-04T00:00:00Z"
        ],
        "party": [
          "No Party"
        ],
        "id": "1ce12ed2-add9-4c65-aeb4-a3c6efb1c5d1",
        "_version_": 1506622425947701200
      }
    ]
  }
}

Conclusion


There are many more options available, but you have now successfully installed Solr and can start using it for your own site.

Thanks.
 

Saturday 16 July 2016

Using Solarium with SOLR and Laravel 5, for Search – Solarium and GUI

Hi Everybody,

After long time i am writing this blog, because i busy somewhere, but now come with some knowledge full thing, that will really help full

In the blog, I introduced the key concepts and we installed and set up SOLR. In this second part we’ll install Solarium, start building an example application, populate the search index and get into a position where we can start running searches.

Creating the Application


Create a new Laravel application via Composer:

composer create-project laravel/laravel movie-search --prefer-dist

Make the storage directory app/storage directory writeable.

Installing Solarium


You’ll recall from the first part that the Solarium Project provides a level of abstraction over the underlying SOLR requests which enables you to code as if SOLR were a native search implementation running locally, rather than worry about issuing HTTP requests or parsing the responses.

By far the best way to install Solarium is using Composer:

"solarium/solarium": "dev-develop"

Alternatively you can download or clone it from Github.

If you’re following along and building the movie search application, this will go in your newly created project’s composer.json file just as you would any other third-party package; there’s no Laravel service provider though, in this case.

Configuring Solarium

The constructor to the Solarium client takes an array of connection details, so create a configuration file – app/config/solr.php as follows:

return array(
    'host'      => '127.0.0.1',
    'port'      => 8983,
    'path'      => '/solr/',
):

If you’ve installed SOLR as per the instructions in the first part these defaults should be just fine, although in some circumstances you may need to change the port number.

For simplicity, we’re simply going to create an instance of the Solarium client as a property of the controller (app/controllers/HomeController.php):

    /**
     * @var The SOLR client.
     */
    protected $client;

    /**
     * Constructor
     **/
    public function __construct()
    {
        // create a client instance      
        $this->client = new \Solarium\Client(Config::get('solr'));
    }
Normally in Laravel you’d create an instance in a service provider bound to the IoC container, but this way will do fine for what’s a pretty simple application.

Ping Queries

A ping query is useful for checking that the SOLR server is running and accessible, and therefore a good place to begin. Using Solarium it’s simple, so you may wish to test if everything is working by using the following:

// create a ping query
$ping = $client->createPing();

// execute the ping query
try {
    $result = $client->ping($ping);
} catch (Solarium\Exception $e) {
    // the SOLR server is inaccessible, do something
}

As the example illustrates, an inaccessible SOLR instance throws an exception, so you can act accordingly by catching it at this point.

Sample Data

For the purposes of this tutorial we’re going to build a simple movie search. I’ve created a CSV file containing around 2,000 movies around a bunch of keywords (for example space, night and house) which you can download, or if you want to create your own, you might want to check out the Rotten Tomatoes API. (As an aside, but one which is related, IMDB make their data available but spread over a number of CSV files – some of which are enormous – and only make them available via the website or over FTP.)

Before we write a command to import this data, let’s look at the basic create, update and delete operations on the SOLR search implementation using Solarium.

Adding Documents to the Search Index
To add a document to the search index, you first need to create an update query instance:

$update = $client->createUpdate();
Then create a document:

$doc = $update->createDocument();    
Now you can treat the document ($doc) as if it were a stdClass and simply assign data as public properties:

$doc->id = 123;
$doc->title = 'Some Movie';
$doc->cast = array('Sylvester Stallone', 'Marylin Monroe', 'Macauley Culkin');
…and so on, before adding the document to the update query:

$update->addDocument($doc);
Then commit the update:

$update->addCommit();
Finally, to actually run the query you call update() on the client:

$result = $client->update($update);
If you wish to verify that you’ve successfully indexed some documents, visit the SOLR admin panel in your browser – typically http://localhost:8983/solr and click Core Admin, you’ll find the number of documents in the index listed as numDocs in the Index section.

Updating Documents

If you need to update a document in the index, you simply need to “re-add” it and – assuming it has the same unique identifier – SOLR will be smart enough to update it, rather than add a new one.

Deleting Documents

You can delete a document from the index using an update query, using syntax not too dissimilar to WHERE clauses in SQL. For example, to delete a document uniquely identified by the ID 123:

// get an update query instance
$update = $client->createUpdate();

// add the delete query and a commit command to the update query
$update->addDeleteQuery('id:123');
$update->addCommit();

// this executes the query and returns the result
$result = $client->update($update);
Or you can be less specific:

// get an update query instance
$update = $client->createUpdate();

// add the delete query and a commit command to the update query
$update->addDeleteQuery('title:test*');
$update->addCommit();

// this executes the query and returns the result
$result = $client->update($update);

Note the use of a wildcard character – in other words: “delete all documents whose title starts with test”.

Populating the Search Index with Movies

Now we’ve looked at the fundamentals of indexing documents, let’s put some data into the index for our sample application.

Laravel makes it easy to build console commands, so let’s create one to import the contents of our movie CSV file and index them. We could also create corresponding database records at this point, but for the purposes of this exercise the indexed documents will contain everything we need.

To create the command, enter the following into the command line:

php artisan command:make PopulateSearchIndexCommand
In the newly-generated file – app/commands/PopulateSearchIndexCommand.php – set the command’s name (i.e., what you enter on the command-line to run it) and the description:

/**
 * The console command name.
 *
 * @var string
 */
protected $name = 'search:populate';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Populates the search index with some sample movie data.';
Now we’ll use the fire() method to create the Solarium client, open the CSV, iterate through it and index each movie:

/**
 * Execute the console command.
 *
 * @return void
 */
public function fire()
{       
    $client = new \Solarium\Client(Config::get('solr'));

    // open up the CSV
    $csv_filepath = storage_path() . '/movies.csv';

    $fp = fopen($csv_filepath, 'r');

    // Now let's start importing
    while (($row = fgetcsv($fp, 1000, ";")) !== FALSE) {

        // get an update query instance
    $update = $client->createUpdate();

    // Create a document
        $doc = $update->createDocument();    

        // set the ID
    $doc->id = $row[0];

    // ..and the title
        $doc->title = $row[1];

        // The year, rating and runtime columns don't always have data
        if (strlen($row[2])) {
            $doc->year = $row[2];
        }
        if (strlen($row[3])) {
            $doc->rating = $row[3];
        }
        if (strlen($row[4])) {
            $doc->runtime = $row[4];
        }

        // set the synopsis
        $doc->synopsis = $row[5];

        // We need to create an array of cast members
        $cast = array();

        // Rows 6 through 10 contain (or don't contain) cast members' names
        for ($i = 6; $i <= 10; $i++) {
            if ((isset($row[$i])) && (strlen($row[$i]))) {
                $cast[] = $row[$i];
            }
        }

        // ...then we can assign the cast member array to the document
        $doc->cast = $cast;

        // Let's simply add and commit straight away.
        $update->addDocument($doc);
    $update->addCommit();

    // this executes the query and returns the result
    $result = $client->update($update);

    }

    fclose($fp);
}
Whilst this isn’t the slickest or most resilient piece of code, it’s a fairly academic exercise which we’re only planning to run once anyway. Ensure the CSV file is in the correct place – app/storage/movies.csv and run it:

php artisan search:populate
All being well, the index should now contain ~2,300 movies. You can check this via the admin interface.

In the next section we’ll start building the basic search in.

The Search Form
Let’s create the search form using Laravel’s Blade templating engine, along with the form builder. So, in app/views/home/index.blade.php:

@extends('layouts.default')

@section('content')

<header>
    {{ Form::open(array('method' => 'GET')) }}
    <div class="input-group">
        {{ Form::text('q', Input::get('q'), array('class' => 'form-control input-lg', 'placeholder' => 'Enter your search term')) }}        
        <span class="input-group-btn">
            {{ Form::submit('Search', array('class' => 'btn btn-primary btn-lg')) }}            
        </span>
    </div>
    {{ Form::close() }}
</header>

@endsection
A basic page layout in app/views/layouts/default.blade.php:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Movie Search</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

</head>
<body>
    <div class="container">
        <header id="header" class="row">        
            <div class="col-sm-12 col-md-12 col-lg-12">
                <h1>Movie Search</h1>
            </div>      
        </header>

        <div class="row">
            <div class="col-sm-12 col-md-12 col-lg-12">
                @yield('content')
            </div>
        </div>

        <hr />

        <footer id="footer">

        </footer>

    </div>

</body>
</html>
In app/controllers/HomeController.php:

public function getIndex()
{
    return View::make('home.index');
}
Finally, replace the contents of app/routes.php with the following, to tell Laravel to use HomeController:

<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
*/
Route::controller('/', 'HomeController');
Now we’re set up and ready to implement the basic search mechanism, which will be the subject of the next part in the series.

Thanks..

Friday 27 May 2016

Updating Column Types with Laravel's Schema Builder

Hi Everybody,

Today we will discuss how to update column type with Laravel 5.1 Schema Builder.

Laravel makes database migrations very easy with its Schema Builder. It has a lot of built-in methods to add tables, columns, indexes, etc. However, it's easy to forget that you can do so much more with just plain old SQL queries.

I needed to change the type of a column from VARCHAR to TEXT. Here's what I ran in a migration file:


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

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

I think this will make you little help.

Thanks.

Friday 20 May 2016

Advertisement script in Jquery

Hi Everybody,


Today we will discuss about advertisement script in Jquery.

All we know in today timing all product required advertisement, so in web application also advertisement display on third party website.When we click on these advertisement, main website of product open either in browser new tab or in any pop up or iframe etc.

For this we require two things

1. Script that is hosted on product website server(inside your project_dir/js_dir/adscript.js )


Code inside your project_dir/js_dir/adscript.js

var siteAddress =  '//yourdomain.com/';
(function() {
    include_jQueryFilesToPage();
})();

function afterloadScript() {
    var adddiv = $('<div class="yourproduct-ad"><div class="yourproduct yourproduct_1279518" id="yourproduct_1279518" data-serve="CV7DPKT"><a rel="nofollow" target="_blank" id="yourproduct_5568645" title="Product Title" class="ad0 odd " href="'+siteAddress+'/route_of_page_you_want_to_open/'" data-title="Product Title" data-width="700" data-height="500"><img width="200" height="200" alt="" src="'+siteAddress+'/images/adscript.png"></a></div></div>');
    $("body").append(adddiv);
    adjustAd();
    var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" id="yourproduct_adscreen" allowfullscreen></iframe>');
    dialog = $("<div id='oopenDiv' style='padding:0'></div>").append(iframe).appendTo("body").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: "auto",
        height: "auto",
        close: function () {
            iframe.attr("src", siteAddress+"route_of_page_you_want_to_open");
        }
    });

    $("#yourproduct_5568645").on("click", function (e) {
        e.preventDefault();
        var src = $(this).attr("href");
        var title = $(this).attr("data-title");
        var width = $(this).attr("data-width");
        var height = $(this).attr("data-height");
        iframe.attr({
            width: +width,
            height: +height,
            src: src
        });
        dialog.dialog("option", "title", title).dialog("open");
    });
    setTimeout($('body').addClass('add_script_wrapper'), 2000);
}


function adjustAd(){
    var iframeHtml = $("body").find(".yourproduct-ad").html();
    $(".adsbyproduct").parent().append('<div class="product-ad">'+iframeHtml+'</div>');
    $("body").find(".yourproduct-ad").remove();
}


function include_jQueryFilesToPage() {
    var jqCSSFilePath = siteAddress + 'css/code.jquery.com-ui-1.10.3-themes-smoothness-jquery-ui.css';
    var jqStyleCSSFilePath = siteAddress + 'css/style.css';
    var jqCoreFilePath = siteAddress + 'js/code.jquery.com-jquery.js';
    var jqUIFilePath = siteAddress + 'js/code.jquery.com-ui-1.10.3-jquery-ui.js';
    var head = document.getElementsByTagName('head')[0];
    // jQuery CSS jnclude
    var jqCSS = 'cssIDJQ';  // you could encode the css path itself to generate id.
    if (!document.getElementById(jqCSS)) {
        var link = document.createElement('link');
        link.id = jqCSS;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = jqCSSFilePath;
        link.media = 'all';
        head.appendChild(link);
    }

    // style CSS jnclude
    var jqStyleCSS = 'styleCssIDJQ';  // you could encode the css path itself to generate id.
    if (!document.getElementById(jqStyleCSS)) {
        var link = document.createElement('link');
        link.id = jqStyleCSS;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = jqStyleCSSFilePath;
        link.media = 'all';
        head.appendChild(link);
    }

    // Core jQuery include
    var jqc = "coreFileRefIDJQ";
    if (!document.getElementById(jqc)) {
        var coreJs = document.createElement('script');
        coreJs.onload = function () {
            //alert("Script loaded and ready");
        };
        coreJs.src = jqCoreFilePath;
        head.appendChild(coreJs);
    }
    // jQueryUI include
    var jqUI = "uiFileRefIDJQ";
    if (!document.getElementById(jqUI)) {
        var coreJsUi = document.createElement('script');
        coreJsUi.onload = function () {
            afterloadScript();
        }
        coreJsUi.src = jqUIFilePath;
        head.appendChild(coreJsUi);
    }
}


2. One line advertisement script that is used by third party website, where you want to display your product advertisement.


Now finally the one line advertisement script(given below) copy and paste the code from below, in every page of the website(where you want to display your ad), just before the closing body tag(inside a div).

<script type="text/javascript" async src= "yourdomain/js/adscript.js"></script><ins class="adsbyproduct"></ins>


Thanks

Friday 13 May 2016

IE Blocking iFrame Cookies

Hi Everybody,

Today we will discuss about "IE Blocking iFrame Cookies".

I have faced a problem in my applications not running correctly from inside an iFrame. I tried it out and it looked like everything worked great in Safari and Firefox but not IE6 or IE7. It took me a few failed attempts to fix it before I decided it must be a session problem. After firing up a packet sniffer it became obvious the cookie with the session ID was not being passed.

The problem lies with a W3C standard called Platform for Privacy Preferences or P3P for short. You can read all about the boring stuff via the link or else just install the P3P Compact Policy header below. This will allow Internet Explorer to accept your third-party cookie. You will need to send the header on every page that sets a cookie.


PHP:

header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

Friday 6 May 2016

How to send email in Laravel 5.1 using SendGrid

Hi Everybody,


Laravel comes with an email sending library built in, so we just need to set it to use SendGrid over SMTP. Check out the docs for Laravel’s mailer for details.

In app/config/mail.php you need to configure these settings:


<?php

return array(
  'driver' => 'smtp',
  'host' => 'smtp.sendgrid.net',
  'port' => 587,
  'from' => array('address' => 'from@example.com', 'name' => 'John Smith'),
  'encryption' => 'tls',
  'username' => 'sendgrid_username',
  'password' => 'sendgrid_password',
);

?>

You can use Laravel’s Mail class just like you normally would, but all email will be sent through SendGrid!


<?php

Mail::send('emails.demo', $data, function($message)
{
    $message->to('jane@example.com', 'Jane Doe')->subject('This is a demo!');
});

?>

Adding a category or custom field


Categories in sendgrid allow you to split your statistics into categories. An example would be if you have a white labeled service you can split your statistics by the user login.

Another useful feature of sendgrid is the notifications. If you want to complete the feedback loop for your product you can pass identifiers as a header which relate to a record in your database which you can then parse the notifications against that record to track deliveries/opens/clicks/bounces.

   

<?php

   Mail::send('emails.view', $data, function ($message)
    {
        $data['category']                  = 'category';
        $data['unique_args']['variable_1'] = 'abc';

        $header = $this->asString($data);

        $message->getSwiftMessage()->getHeaders()->addTextHeader('X-SMTPAPI', $header);

        $message->to('jane@example.com', 'Jane Doe')->subject('This is a demo!');
    });


    private function asJSON($data) // set as private with the expectation of being a class method
    {
        $json = json_encode($data);

        $json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);

        return $json;
    }

    private function asString($data) // set as private with the expectation of being a class method
    {
        $json = $this->asJSON($data);
        $str  = wordwrap($json, 76, "\n   ");

        return $str;
    }
?>

Thanks.

Friday 29 April 2016

Custom helpers in Laravel 5.1


Hi Everybody,

Today we will discuss about how to create custom helpers in laravel 5.1

Many times we create some function that further used in different controllers. To avoid multiple creation of same function in multiple controller, we can write these common function in helpers.

 

 Custom helpers’ directory


Our helpers will be located in the /app directory

Create a new directory Helpers in /app/Helpers

 

Helper class definition


Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code

<?php

namespace App\Helpers;

class MyFuncs {

    public static function full_name($first_name,$last_name) {
        return $first_name . ', '. $last_name;  
    }
}


HERE,

    1. namespace App\Helpers; defines the Helpers namespace under App namespace
    2. class MyFuncs {…} defines the helper class MyFuncs
    3. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string

 

Helpers service provide class


Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.

Run the following artisan command

php artisan make:provider HelperServiceProvider

The file will be created in /app/Providers/HelperServiceProvider.php

Open /app/Providers/HelperServiceProvider.php

Add the following code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {

   /**
    * Bootstrap the application services.
    *
    * @return void
    */
   public function boot()
   {
      //
   }

   /**
    * Register the application services.
    *
    * @return void
    */
   public function register()
   {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
   }
}
HERE,

    1. namespace App\Providers; defines the namespace provider
    2. use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
    3. class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
    4. public function boot(){…} bootstraps the application service
    5. public function register(){…} is the function that loads the helpers
    6. foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.

 

Helper Service Provider and class alias configuration


We now need to register the HelperServiceProvider and create an alias for our helpers.

Open /config/app.php file

Locate the providers array variable

Add the following line

App\Providers\HelperServiceProvider::class,

Locate the aliases array variable

Add the following line

'MyFuncs' => App\Helpers\MyFuncs::class,

Save the changes
Using our custom helper

Add the following route definition

<?php

namespace App\Http\Controllers;

use App\Helpers\MyFuncs;

class CustomerController extends Controller
{

    public function getCustomerName($id)
    {
        $response = $this->getCustomerDetail($id);
        $msg = "Customer detail.";
        return MyFuncs::
full_name($response->first_name, $response->last_name);
    }

}

Custom helpers can be used for commonly performed tasks. They are mostly helpful in views where you do not want to include business logic. You can create custom functions that format or process the data and return the results

Thanks.

Friday 22 April 2016

Conditionally Loading Service Providers in Laravel 5.1

Hi 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.

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

Thanks.

Friday 15 April 2016

How to implement Model Validation in Laravel 5.1

Hi Everybody,

Model validation is the method of establishing rules to ensure when you’re creating, or updating, an object based on a model, that all of its field values are set appropriately. That all required fields are filled, that all date fields are formatted properly, etc.

We’re going to use the Esensi Model Traits package for model validation.

To install it, open up your app’s composer.json file and add its entry:

  "require": {
    // …
    "esensi/model": "0.5.*"
  }

Next, open the command line, move into your application’s main directory (remember to connect to your virtual machine first if you’re using Homestead), and update Composer to install it:

$ composer update

Finally, to activate the Esensi functionality in the Car model, simply replace:

use Illuminate\Database\Eloquent\Model;

class Car extends Model
// …
with:

use \Esensi\Model\Model;

class Car extends Model
// …
And then you can establish the model’s validation rules by adding a $rules array to the model:

class Car extends Model
{
    protected $rules = [
        'make' => ['required'],
        'model' => ['required'],
    ];
}

The $rules array defines rules for any/all of the model’s fields, and you can use any of Laravel’s built-in validation rules in the individual fields’ rules arrays.

With that established, we can build out the store action in the CarController to handle the Create Car page’s form submissions.

Handling Form Submissions


To start, in the store action, we create a new Car object, populate it with the submitted form data, and then attempt to save it. The save function returns a boolean value, so if it fails — thanks to the Esensi model validation — we can act accordingly, inside that if statement.

And if it succeeds, we can handle that below the if statement (which it will never hit, in that case).

  public function store(Request $request) {
    $car = new \App\Car;

    // populate the model with the form data
    $car->make = $request->make;
    $car->model = $request->model;

    // save the model to create a new object in the database
    if (!$car->save()) {

    }

    // success!
    
  }

Upon failure, we need to: retrieve the validation errors; redirect back to the create page, passing along those errors & the submitted form data (for repopulating the form).

And if it succeeds, we redirect back to the create page (or another page of your choosing), and pass along a “success” message.

Both scenarios are demonstrated here:

  public function store(Request $request) {
    //…
    // save the model to create a new object in the database
    if (!$car->save()) {
      $errors = $car->getErrors();
      return redirect()
            ->action('CarController@create')
        ->with('errors', $errors)
        ->withInput();
    }

    // success!
    return redirect()
      ->action('CarController@create')
      ->with('message', 'Your '. $car->make . ' ' 
                . $car->model . ' has been created!');
  }

Esensi provides the getErrors function to retrieve the validation errors, and then we pass them along via the redirect using the with function.

And Laravel provides the withInput function to pass along all of the form data that was submitted. And thanks to the use of the Forms library’s Form::model function (in the Laravel 5 Application Form Model Binding tutorial) to create a form with model binding, the form will automatically be repopulated without writing any additional code.

Last step: to display those status messages in the view.


Displaying Status Messages

When you pass data during a redirect, it’s “flashed” to the session, meaning it’s only accessible on the next page load. You retrieve session data in Laravel using the session function, passing the key of the object, you’re looking for.

Both the errors object (which contains the validation errors) and the success message were passed using the with function, so you can retrieve both from the session:

      // …
      <div class="page-header">
        <h1>Create a Car</h1>
      </div>

      @if (count(session('errors')) > 0)
      <div class="alert alert-danger">
        @foreach (session('errors')->all() as $error)
          {{ $error }}<br>
        @endforeach
      </div>
      @endif

      @if (session('message'))
      <div class="alert alert-success">
        {{ session('message') }}
      </div>
      @endif

      // …
You call the all function on the errors object to retrieve an array with all the error messages. And then you can just loop through and print out each one, wrapping them in a Bootstrap alert.

And for the success message, we just look for it, and, if found, print it out in another Bootstrap alert.

So now, if you submit the form without all the required values, you’ll see the validation errors appear.



And if you submit the form with all the required data, the car will be created and you’ll see the “success” message.



Thanks.

Friday 8 April 2016

How to add event to different Calendars(Google Calendar, Icalendar, Outlook Calendar, Yahoo Calendar etc.) in Laravel 5.1

Hi Everybody,

Today we will discuss about how to add event to different Calendars(Google Calendar, ICalendar, Outlook Calendar, Yahoo Calendar etc.) in Laravel 5.1

Generally in time event type application we need to add events to different calendars like google calendar,  ICalendar, Outlook Calendar, Yahoo Calendar etc.

In Laravel we will implement it by using below code(in your blade template).

<html>
<head>
    <!-- 1. Include style -->
    <link href="http://addtocalendar.com/atc/1.5/atc-style-blue.css" rel="stylesheet" type="text/css">
</head>
<body>
    <!-- 2. Include script -->
    <script type="text/javascript">(function () {
            if (window.addtocalendar)if(typeof window.addtocalendar.start == "function")return;
            if (window.ifaddtocalendar == undefined) { window.ifaddtocalendar = 1;
                var d = document, s = d.createElement('script'), g = 'getElementsByTagName';
                s.type = 'text/javascript';s.charset = 'UTF-8';s.async = true;
                s.src = ('https:' == window.location.protocol ? 'https' : 'http')+'://addtocalendar.com/atc/1.5/atc.min.js';
                var h = d[g]('body')[0];h.appendChild(s); }})();
    </script>

    <!-- 3. Place event data -->
    <span class="addtocalendar atc-style-blue">
        <var class="atc_event">
            <var class="atc_date_start">2016-05-04 12:00:00</var>
            <var class="atc_date_end">2016-05-04 18:00:00</var>
            <var class="atc_timezone">Europe/London</var>
            <var class="atc_title">Star Wars Day Party</var>
            <var class="atc_description">May the force be with you</var>
            <var class="atc_location">Tatooine</var>
            <var class="atc_organizer">Luke Skywalker</var>
            <var class="atc_organizer_email">luke@starwars.com</var>
        </var>
    </span>
</body>
</html>

In event data write your event detail accordingly.

Thanks.

Friday 1 April 2016

Smooth scroll when click a map marker

Hi Everybody,

Today we will discuss about how to make a smooth scroll when click a map marker.

Html Code

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery.js"></script>
</head>
<body>
<div id='map_canvas' style="width: 500px;height: 500px"></div>
<div id='1'>
    <h1>1</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    </p>
</div>
<div id='2'><h1>2</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    </p>

</div>

Jquery Code

<script>
jQuery(function($) {
    // Asynchronously Load the map API
    var script = document.createElement('script');
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.22&callback=initialize";
    document.body.appendChild(script);
});

function attachClickHandler(marker){
google.maps.event.addListener(marker, 'click', function() {

var elem = $(marker.url);
console.log(marker.url);
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000 );

});
}

function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);

// Multiple Markers
var markers = [
['London Eye, London', 51.503454,-0.119562, '#1'],
['Palace of Westminster, London', 51.499633,-0.124755, '#2']
];



// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
url: markers[i][3]
});
attachClickHandler(marker);
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});

}
</script>
</body>
</html>

Thanks

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

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.