Laravel 5 login with google oauth apiclient example.
In my previous tutorial, you will learn, how to login with facebook now i am going to tell you that how you can login with google in laravel 5.2.
To authenticate with google you need client id, client secret and api key so you must have these credentials before processing with login with google.
Here using this code, you can login and register via google.
Step1: Install Laravel 5.2If Laravel is not installed in your system then first install with following command and get fresh Laravel project.
composer create-project --prefer-dist laravel/laravel blogStep 2: Create users table and model
Now you will create a User table in your database, first go through with PHP artisan command to create migration file for user table.
So first fire this command :php artisan make:migration create_users_table
After fire this command you will see a migration file in database/migrations. You will simply put following code in your migration file to create user table.
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateUsersTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public function up()
- {
- Schema::create('users', function (Blueprint $table) {
- $table->increments('id');
- $table->string('name');
- $table->string('email')->unique();
- $table->string('password');
- $table->rememberToken();
- $table->timestamps();
- });
- }
- /**
- * Reverse the migrations.
- *
- * @return void
- */
- public function down()
- {
- Schema::drop('users');
- }
- }
Save this migration file and run following command.
php artisan migrateapp/User.php
- namespace App;
- use Illuminate\Foundation\Auth\User as Authenticatable;
- class User extends Authenticatable
- {
- /**
- * The attributes that are mass assignable.
- *
- * @var array
- */
- protected $fillable = [
- 'name', 'email', 'password',
- ];
- /**
- * The attributes that should be hidden for arrays.
- *
- * @var array
- */
- protected $hidden = [
- 'password', 'remember_token',
- ];
- }
Put following line in your composer file and update your composer to download package:
"google/apiclient": "2.0.*"Step4: Route File
Now add following routes in your routes.php
- Route::get('glogin',array('as'=>'glogin','uses'=>'UserController@googleLogin')) ;
- Route::get('google-user',array('as'=>'user.glist','uses'=>'UserController@listGoogleUser')) ;
Now create User Controller file in following path app/Http/Controllers/
app/Http/Controllers/UserController.php
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Http\Controllers\Controller;
- use App\User;
- class UserController extends Controller
- {
- public function googleLogin(Request $request) {
- $google_redirect_url = route('glogin');
- $gClient = new \Google_Client();
- $gClient->setApplicationName(config('services.google.app_name'));
- $gClient->setClientId(config('services.google.client_id'));
- $gClient->setClientSecret(config('services.google.client_secret'));
- $gClient->setRedirectUri($google_redirect_url);
- $gClient->setDeveloperKey(config('services.google.api_key'));
- $gClient->setScopes(array(
- 'https://www.googleapis.com/auth/plus.me',
- 'https://www.googleapis.com/auth/userinfo.email',
- 'https://www.googleapis.com/auth/userinfo.profile',
- ));
- $google_oauthV2 = new \Google_Service_Oauth2($gClient);
- if ($request->get('code')){
- $gClient->authenticate($request->get('code'));
- $request->session()->put('token', $gClient->getAccessToken());
- }
- if ($request->session()->get('token'))
- {
- $gClient->setAccessToken($request->session()->get('token'));
- }
- if ($gClient->getAccessToken())
- {
- //For logged in user, get details from google using access token
- $guser = $google_oauthV2->userinfo->get();
- $request->session()->put('name', $guser['name']);
- if ($user =User::where('email',$guser['email'])->first())
- {
- //logged your user via auth login
- }else{
- //register your user with response data
- }
- return redirect()->route('user.glist');
- } else
- {
- //For Guest user, get google login url
- $authUrl = $gClient->createAuthUrl();
- return redirect()->to($authUrl);
- }
- }
- public function listGoogleUser(Request $request){
- $users = User::orderBy('id','DESC')->paginate(5);
- return view('users.list',compact('users'))->with('i', ($request->input('page', 1) - 1) * 5);;
- }
- }
- @extends('layouts.default')
- @section('content')
- <div class="row">
- <div class="col-lg-12 margin-tb">
- <div class="pull-left">
- <h2>Logged Google User List</h2>
- </div>
- <div class="pull-right">
- <a class="btn btn-danger" href="{{ route('glogin') }}"> Login with Google</a>
- </div>
- </div>
- </div>
- <table class="table table-bordered">
- <tr>
- <th>No</th>
- <th>Name</th>
- <th>Login Time</th>
- </tr>
- @foreach ($users as $user)
- <tr>
- <td>{{ ++$i }}</td>
- <td>{{ $user->name }}</td>
- <td>{{ $user->updated_at->diffForHumans() }}</td>
- </tr>
- @endforeach
- </table>
- {!! $users->render() !!}
- @endsection
To get client_id, client_secret and api_key you have to create a app within google console and generate these tokens.
Now you can try this code in your application for google login and register in Laravel 5.2.
Click here to see the demo for login with google in Laravel 5.2