Laravel 5 login with google oauth apiclient example
In this post we will give you information about Laravel 5 login with google oauth apiclient example. Hear we will give you detail about Laravel 5 login with google oauth apiclient exampleAnd how to use it also give you demo for it if it is necessary.
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.2
If 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 blog
Step 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 IlluminateDatabaseSchemaBlueprint;
- use IlluminateDatabaseMigrationsMigration;
- class CreateUsersTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public functionup()
- {
- 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 functiondown()
- {
- Schema::drop('users');
- }
- }
use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;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 migrate
app/User.php
- namespace App;
- use IlluminateFoundationAuthUser 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',
- ];
- }
namespace App;use IlluminateFoundationAuthUser 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', ];}
Step3: Update Composer File to add Google apiclient libraries
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'));
Route::get('glogin',array('as'=>'glogin','uses'=>'UserController@googleLogin')) ;Route::get('google-user',array('as'=>'user.glist','uses'=>'UserController@listGoogleUser')) ;
Step5: User Controller
Now create User Controller file in following path app/Http/Controllers/
app/Http/Controllers/UserController.php
- <?php
- namespace AppHttpControllers;
- use IlluminateHttpRequest;
- use AppHttpControllersController;
- use AppUser;
- class UserController extends Controller
- {
- public functiongoogleLogin(Request $request){
- $google_redirect_url=route('glogin');
- $gClient=newGoogle_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=newGoogle_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
- }
- returnredirect()->route('user.glist');
- }else
- {
- //For Guest user, get google login url
- $authUrl=$gClient->createAuthUrl();
- returnredirect()->to($authUrl);
- }
- }
- public functionlistGoogleUser(Request $request){
- $users= User::orderBy('id','DESC')->paginate(5);
- returnview('users.list',compact('users'))->with('i',($request->input('page',1)-1)*5);;
- }
- }
<?phpnamespace AppHttpControllers;use IlluminateHttpRequest;use AppHttpControllersController;use AppUser;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);; }}
Step 6: Create Laravel Blade File to list User who login with google
- @extends('layouts.default')
- @section('content')
- <divclass="row">
- <divclass="col-lg-12 margin-tb">
- <divclass="pull-left">
- <h2>Logged Google User List</h2>
- </div>
- <divclass="pull-right">
- <aclass="btn btn-danger"href="{{ route('glogin') }}"> Login with Google</a>
- </div>
- </div>
- </div>
- <tableclass="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
@extends('layouts.default') @section('content') <div > <div > <div > <h2>Logged Google User List</h2> </div> <div > <a href="{{ route('glogin') }}"> Login with Google</a> </div> </div> </div> <table > <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
Hope this code and post will helped you for implement Laravel 5 login with google oauth apiclient example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs