Step 1: Install Laravel 8
Create a new Laravel 8 project and navigate to the project folder:
Step 2: Install Socialite
Install the Socialite package via Composer, which provides the functionality for connecting with Google:
Once installed, add the following lines to the config/app.php
file to register the provider and alias:
-
Add provider in the
providers
array:
-
Add alias in the
aliases
array:
Step 3: Create a Google App
-
Go to Google Developers Console.
-
Create a new project.
-
Navigate to
Credentials
and clickCreate Credentials
, then selectOAuth 2.0 Client ID
. -
Configure the consent screen, then set the application type to
Web application
. -
Add
http://localhost:8000
as an authorized JavaScript origin. -
Add
http://localhost:8000/auth/google/callback
as an authorized redirect URI. -
Copy the
Client ID
andClient Secret
.
Step 4: Configure the Google API Keys in Laravel
Open config/services.php
and add the following configuration for Google:
Now, add these values to the .env
file:
Step 5: Install Laravel UI and Generate Auth Scaffolding
Next, we need to install laravel/ui
to generate the authentication scaffolding.
-
Install Laravel UI:
-
Generate the authentication scaffolding:
-
Install dependencies using NPM:
Step 6: Add Google ID to the User Table
We need to add a google_id
column to the users
table. Run the following command to generate a migration:
Edit the migration file to add the google_id
column:
Run the migration:
Now, update the User
model to allow mass assignment for google_id
:
Step 7: Define Routes for Google Authentication
In routes/web.php
, add the following routes for Google authentication:
Step 8: Create GoogleController
Create a new controller for handling Google authentication:
In app/Http/Controllers/Auth/GoogleController.php
, add the following methods:
Step 9: Update the Login Blade View
In resources/views/auth/login.blade.php,
Add a Google login button to the login form:
Step 10: Run the Application
Now that everything is set up, start your Laravel development server:
Visit http://localhost:8000/login
, and you should see a "Login With Google" button on your login page. Clicking it will redirect you to Google, and once you authenticate, you’ll be logged into your Laravel application.
That's it! You've now integrated Google login in your Laravel 8 application using Socialite. If you have any further questions or need additional functionality, feel free to ask!