September 03, 2024 • 7 min read
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.
Before diving into the code, make sure you have the following:
First things first, you’ll need to create credentials for the Google Calendar API.
http://yourapp.com/oauth2callback
.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
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.
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.
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.
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.
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');
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
Sr. Software Engineer
I have over 6 years of experience building highly scalable web applications using a wide variety of technologies. Currently focusing on Laravel, Livewire, Vue.js and AWS as my go-to stack.
If you enjoy the content that I make, you can subscribe and receive insightful information through email. No spam is going to be sent, just updates about interesting posts or specialized content that I talk about.
Ready to take your project to the next level?
Contact me