How to integrate Google Calendar with Laravel
Step-by-step guide to connecting the Google Calendar API to Laravel: OAuth 2.0 credentials, a service class, the auth flow and creating events.
How to Seamlessly Integrate Google Calendar into Your Laravel App
Integrating Google Calendar into your Laravel application can be a game-changer, especially if you need to manage events, schedule appointments, or keep track of deadlines. In this guide, I’ll walk you through the process, from setting up your Google API to syncing events in your Laravel app.
Prerequisites
Before diving into the code, make sure you have the following:
- A Laravel application (I’m using Laravel 8, but this should work with newer versions as well).
- A Google account with access to Google Calendar.
- Basic understanding of Laravel routes, controllers, and views. (If this is something you don't have, tutorial coming soon!)
Step 1: Set Up Google API Credentials
First things first, you’ll need to create credentials for the Google Calendar API.
- Go to the Google Cloud Console: Head over to Google Cloud Console.
- Create a New Project: If you don’t have a project already, create one. Name it something meaningful like “Laravel Google Calendar Integration.”
- Enable Google Calendar API: In the API Library, search for “Google Calendar API” and enable it for your project.
- Create OAuth 2.0 Credentials: Navigate to the “Credentials” section. Click on “Create Credentials” and choose “OAuth 2.0 Client IDs.” Configure the consent screen and add your application details. Then, generate the client ID and client secret. You’ll need these later.
- Set Up Redirect URI: Add a redirect URI for your application, which will be used to handle the OAuth callback. It should look something like this:
http://yourapp.com/oauth2callback.
Step 2: Install Google Client Library
Now that we have the credentials, we’ll need to install the Google Client Library in our Laravel app. This library makes it easy to interact with Google APIs.
composer require google/apiclient:^2.0
Step 3: Set Up Environment Variables
Next, add your Google API credentials to your .env file. This keeps your sensitive data secure and allows you to easily change configurations between environments.
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=http://yourapp.com/oauth2callback
Make sure to replace the placeholders with your actual client ID, client secret, and redirect URI.
Step 4: Create Google Calendar Service
To keep our code organized, we’ll create a service class that handles all interactions with the Google Calendar API.
Create a Service Class: In your app/Services directory, create a new class called GoogleCalendarService.php.
<?php
namespace App\Services;
use Google\Client;
use Google\Service\Calendar;
class GoogleCalendarService {
protected $client;
protected $calendarService;
public function __construct() {
$this->client = new Client();
$this->client->setClientId(config('services.google.client_id'));
$this->client->setClientSecret(config('services.google.client_secret'));
$this->client->setRedirectUri(config('services.google.redirect'));
$this->client->addScope(Calendar::CALENDAR);
$this->calendarService = new Calendar($this->client);
}
public function authenticate($code) {
$this->client->authenticate($code);
session(['google_access_token' => $this->client->getAccessToken()]);
}
public function getClient() {
if (session('google_access_token')) {
$this->client->setAccessToken(session('google_access_token'));
}
return $this->client;
}
public function listEvents($calendarId = 'primary') {
$this->getClient();
$events = $this->calendarService->events->listEvents($calendarId);
return $events->getItems();
}
public function createEvent($eventData, $calendarId = 'primary') {
$this->getClient();
$event = new \Google\Service\Calendar\Event($eventData);
$event = $this->calendarService->events->insert($calendarId, $event);
// You can also insert the event in DB to retrieve it from there later
return $event;
}
}
This class handles authentication, event listing, and event creation with Google Calendar.
Step 5: Set Up OAuth Flow
To allow users to authenticate with their Google account, we’ll set up routes and controllers for the OAuth flow.
Routes: Add the following routes in your web.php file:
use App\Http\Controllers\GoogleCalendarController;
Route::get('auth/google', [GoogleCalendarController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleCalendarController::class, 'handleGoogleCallback']);
Controller: Create a GoogleCalendarController.php in the app/Http/Controllers directory.
<?php
namespace App\Http\Controllers;
use App\Services\GoogleCalendarService;
use Illuminate\Http\Request;
class GoogleCalendarController extends Controller {
protected $googleService;
public function __construct(GoogleCalendarService $googleService) {
$this->googleService = $googleService;
}
public function redirectToGoogle() {
return redirect()->away($this->googleService->getClient()->createAuthUrl());
}
public function handleGoogleCallback(Request $request) {
$this->googleService->authenticate($request->get('code'));
return redirect('/')->with('success', 'Google Calendar connected!');
}
}
This controller handles redirecting users to Google’s OAuth consent screen and processing the callback.
Step 6: Display and Manage Calendar Events
Now that authentication is set up, we can start interacting with Google Calendar. Let's display a list of events on a simple view.
Add a Method in the Controller: Update GoogleCalendarController.php to include a method for displaying events.
public function showEvents() {
$events = $this->googleService->listEvents();
return view('events.index', compact('events'));
}
Create a View: In your resources/views/events/ directory, create an index.blade.php file.
@extends('layouts.app')
@section('content')
<h1>Google Calendar Events</h1>
@if(count($events) > 0)
<ul>
@foreach($events as $event)
<li>{{ $event->getSummary() }} ({{ $event->getStart()->getDateTime() }})</li>
@endforeach
</ul>
@else
<p>No events found.</p>
@endif
@endsection
This view will loop through the events fetched from Google Calendar and display them.
Step 7: Add a New Event to Google Calendar
To add a new event, we need a form where users can input event details.
Create a Form: Add a form to the index.blade.php view for creating new events.
<form action="{{ route('events.store') }}" method="POST">
@csrf
<input type="text" name="summary" placeholder="Event Title">
<input type="datetime-local" name="start">
<input type="datetime-local" name="end">
<button type="submit">Add Event</button>
</form>
Store the Event: Add a method in GoogleCalendarController.php to handle form submission.
public function storeEvent(Request $request) {
$eventData = [
'summary' => $request->summary,
'start' => ['dateTime' => $request->start],
'end' => ['dateTime' => $request->end],
];
$event = $this->googleService->createEvent($eventData);
return redirect()->back()->with('success', 'Event created: ' . $event->getSummary()); }
Add the Route: Finally, add a route to handle event creation.
Route::post('events', [GoogleCalendarController::class, 'storeEvent'])->name('events.store');
Conclusion
While there are some 3rd party packages that already contain some of this functionality, it's a good idea to do it yourself for the purpose of learning or if you want to have full control of the codebase for your platform. Not to mention, you'll be entirely responsible for maintaining the code, which is a good thing if you take into consideration that if you go for a 3rd party package, the package may be outdated for years.
That being said, it's also a good idea to extend this concept and build up some automation, for example, making a cron job that grabs the events after X amount of minutes, stores them into DB and then displays into a calendar, for example. This way, you can save up some API calls, improve the performance, and start combining different pieces into what a potential SaaS could be.
As you can see, integrating the Google Calendar is relatively easy, specially during the development phase. Keep in mind that you're going to go Production mode, Google needs to review your app for which you need to provide some documents (such as privacy policy, EULA, terms of usage, etc.)
Liked the post? Share it to spread the knowlege!
-Gonza
Need a hand with a Laravel codebase or a build like this one? Take a look at my Laravel consulting services.