Login with Laravel 8 and Socialite, Google
Step 1: Install Laravel 8
step: Install UI
Note:
composer require laravel/ui
php artisan ui vue --auth
First, install a new Laravel app just running the below command in your terminal.
composer create-project --prefer-dist laravel/laravel Laravel_Login_Google
Step 2: Update Your Database Credentials
After that update your database credentials in your .env file which is located in your project root.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_custom_auth
DB_USERNAME=root
DB_PASSWORD=#your database password
GOOGLE_CLIENT_ID="your google id"
GOOGLE_CLIENT_SECRET="your secret"
Step 3: Create Laravel Authentication
Now the basic authentication we need to run the auth command of Laravel just running the below command.
php artisan make:auth
After running this you check-in web.php have added auth routes automatically. These routes work Laravel inbuilt function.
Step 4: Download Socialite Package
The Laravel socialite package makes authentification with traditional social networks simple. So download the socialite package just running the below command.
composer require laravel/socialite
composer self-update --2
now open the config\services.php and add the below code on it.
config\services.php
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => 'http://localhost/Laravel_Login_Google/public/login/google/callback',
],
Step 5: Get secrets from Google
Here we get CLIENT ID and CLIENT SECRET for the google login button in Laravel based project, So we need to go https://console.developers.google.com/ and create an app. Create an app in the config/service.php file just like below.
1) First Go to the dashboard and click select the new project you get a popup just like below. add your new app name and your google email id on it.
Now our App settings are done, copy your client id, client secret, and predict you're and save in .env file.
Step 6: Make Migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('provider_id')->nullable();
$table->text('avatar')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
After adding the migration file now run the migrate command.
php artisan migrate
Step 7: Add Routes
In this step we create routes for Facebook login, add two routes in your web.php file.
app/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// Google login
Route::get('login/google', [App\Http\Controllers\Auth\LoginController::class, 'redirectToGoogle'])->name('login.google');
Route::get('login/google/callback', [App\Http\Controllers\Auth\LoginController::class, 'handleGoogleCallback']);
// -----------------------------forget password ------------------------------
Route::get('forget-password', 'App\Http\Controllers\Auth\ForgotPasswordController@getEmail')->name('forget-password');
Route::post('forget-password', 'App\Http\Controllers\Auth\ForgotPasswordController@postEmail')->name('forget-password');
Route::get('reset-password/{token}', 'App\Http\Controllers\Auth\ResetPasswordController@getPassword');
Route::post('reset-password', 'App\Http\Controllers\Auth\ResetPasswordController@updatePassword');
Step 8: Create LoginController
php artisan make:controller LoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
// Google login
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
// Google callback
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->user();
$this->_registerOrLoginUser($user);
// Return home after login
return redirect()->route('home');
}
protected function _registerOrLoginUser($data)
{
$user = User::where('email', '=', $data->email)->first();
if (!$user) {
$user = new User();
$user->name = $data->name;
$user->email = $data->email;
$user->provider_id = $data->id;
$user->avatar = $data->avatar;
$user->save();
}
Auth::login($user);
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
// Google login
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
// Google callback
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->user();
$this->_registerOrLoginUser($user);
// Return home after login
return redirect()->route('home');
}
protected function _registerOrLoginUser($data)
{
$user = User::where('email', '=', $data->email)->first();
if (!$user) {
$user = new User();
$user->name = $data->name;
$user->email = $data->email;
$user->provider_id = $data->id;
$user->avatar = $data->avatar;
$user->save();
}
Auth::login($user);
}
}
Step 9: Add Button in Login Page
Add the below code in your login.blade.php file.
Resources/Views/passwords/Auth/login.blade.php
Add the below code in your login.blade.php file.
Resources/Views/passwords/Auth/login.blade.php
@extends('layouts.app') @section('content') <div class="login-form"> <form method="POST" action="{{ route('login') }}"> @csrf <div class="text-center"> <a href="" aria-label="Space"> <img class="mb-3 logo-image" src="{{URL::to('assets/images/logo_log.png')}}" alt="Logo" width="60" height="60"> </a> </div> <div class="text-center mb-4"> <h1 class="h3 mb-0">Please sign in</h1> <p>Signin to manage your account.</p> </div> @if(session()->has('error')) <div class="alert alert-danger"> {{ session()->get('error') }} </div> @endif <div class="js-form-message mb-3"> <div class="js-focus-state input-group form"> <div class="input-group-prepend form__prepend"> <span class="input-group-text form__text"> <i class="fa fa-envelope form__text-inner"></i> </span> </div> <input type="email" class="form-control form__input @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" placeholder="Email" autocomplete="email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-lock"></i> </span> </div> <input type="password" class="form-control @error('password') is-invalid @enderror" name="password" placeholder="Password" autocomplete="new-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3"> <div class="col-6"> <!-- Checkbox --> <div class="custom-control custom-checkbox d-flex align-items-center text-muted"> <input class="custom-control-input"type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}> <label class="custom-control-label" for="remember"> Remember Me </label> </div> <!-- End Checkbox --> </div> </div> <div class="form-group mb-3"> <button type="submit" class="btn btn-primary login-btn btn-block">Signup</button> </div> <div class="text-center mb-3"> <p class="text-muted">Have an account? <a href="{{route('register')}}">Signin</a></p> </div> <div class="or-seperator"><i>OR</i></div> <div class="row mx-gutters-2 mb-4"> <div class="col-sm-4"> <a href="{{ route('login.google') }}"> <button type="button" class="btn btn-block btn-google"> <i class="fa fa-google mr-2"></i>Google </button> </a> </div> </div> <p class="small text-center text-muted mb-0">All rights reserved. © Space. 2021 soengsouy.com.</p> </form> </div> @endsection
Step 9: Run Development Server
After successfully update all run the development server just adding the below command in the terminal.
php artisan serve
After this go to the browser and check using the login page.
http://localhost/Laravel_Login_Google/public/
1 Comments
Thank you for sharing your knowledge. This tutorial was everything I needed. Thanks.
ReplyDeleteCAN FEEDBACK
Emoji