Seamless Data Synchronization: HubSpot Integration with Laravel

Tejas Prajapati
Simform Engineering
6 min readAug 7, 2023

Achieve business brilliance through the harmonious HubSpot-Laravel integration.

What is HubSpot?

HubSpot is an integrated CRM platform with tools for marketing, sales, and customer service. It aids businesses in attracting, engaging, and satisfying customers through features such as CRM, email marketing, social media management, and analytics. Its user-friendly interface and integrations simplify marketing, lead tracking, and campaign measurement, fostering business growth via personalized experiences and robust customer relationships.

Why integrate HubSpot with Laravel

HubSpot features seamlessly enhance web apps for an efficient, personalized user experience with the Laravel framework. The robust PHP framework Laravel forms a reliable foundation for online applications. Integrating HubSpot CRM into Laravel enables effortless lead generation, email scheduling, and customer interaction tracking.

Companies can use HubSpot forms to directly collect user data from Laravel-based websites. This data can be processed and stored in the Laravel application database for streamlined lead management. Integration with HubSpot’s email marketing enables personalized and automated campaigns based on user behavior, boosting engagement and conversions.

HubSpot’s CRM, combined with Laravel’s dynamic development, offers a robust solution for enhancing customer engagement and operational efficiency.

Steps for HubSpot Account Setup

First, we need to create a HubSpot account. Click here to create one.
After creating, follow the below steps:

1. Create HubSpot Access Token: Go to Settings > Private App > Create App. Now switch to Auth tab to get Access Token for API call.

2. Create HubSpot Form: Go to Marketing > Lead Capture > Form. Finally, obtain the form script for use in our blade file.

3. Create Email Template: Go to Marketing > Email. Design the desired Email Template for our workflow to send emails to new contacts upon form submission.

4. Create HubSpot Workflow: Go to Automation > Workflow. Choose Contact Based Workflow and select “form submission” as a trigger. For the action, choose “send email” and select the template created in step 3.

So, when we insert the form code in our Laravel app, and the user submits it, this triggers the workflow to send a welcome email from Hubspot.

Steps for Laravel 8 and HubSpot Integration

  • Step 1: Install a fresh new Laravel 8 application
  • Step 2: Install hubspot-apiclient Package
  • Step 3: Set HubSpot API Key
  • Step 4: Create Controller File
  • Step 5: Create Routes
  • Step 6: Create Blade File
  • Step 7: Testing
  • Step 8: Conclusion

Step 1: Install a fresh new Laravel 8 application

Let us begin with installing a new Laravel application. If you have already created the project, skip this step.

composer create-project laravel/laravel hubspot-integration

Step 2: Install hubspot-apiclient package

Install hubspot-apiclient via the Composer package manager. This is required to communicate with HubSpot using the API key we have generated during HubSpot setup.

composer require hubspot/api-client

Step 3: Set HubSpot API key

Add the HubSpot access token we have created in Hubspot Setup Step 1 in .env file.

HUBSPOT_ACCESS_TOKEN = your_hubspot_access_token

Step 4: Create a controller file

Here, create a new controller as UserController and write a method like the one below.

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\HubspotContact;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\View\View;

class UserController extends Controller
{
/**
* This function is used to fetch contact list from hubspot
*
* @param Request $request
* @return JsonResponse
*/
public function userList(Request $request): JsonResponse
{
try {
$contacts = collect(getContact());
$datatablesData = $contacts->map(function ($contact) {
return [
'id' => $contact['id'],
'first_name' => $contact['properties']['firstname'] ?? '',
'last_name' => $contact['properties']['lastname'] ?? '',
'email' => $contact['properties']['email'] ?? '',
'createdate' => $contact['properties']['createdate'] ?? '',
'lastmodifieddate' => $contact['properties']['lastmodifieddate'] ?? ''
];
});

if ($request->ajax()) {
return Datatables::of($datatablesData)->addIndexColumn()
->make(true);
}
} catch (\Exception $e) {
echo 'Error : '.$e->getMessage();
}
}

/**
* This function is used to display contact list from hubspot
*
* @return View
*/
public function displayUser(): View
{
return view('home');
}

/**
* This function is used to display signup form for contact
*
* @return View
*/
public function signupUser(): View
{
return view('singup_news');
}
}

Here is the Helpers.php file in which we have written HubSpot logic provided by Hubspot for PHP SDK. You may view the API docs here.

<?php

use App\Models\HubspotContact;
use HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput;
use HubSpot\Factory;
use HubSpot\Client\Crm\Contacts\ApiException;

if (!function_exists('getContact')) {

function getContact()
{
$client = Factory::createWithAccessToken(env('HUBSPOT_ACCESS_TOKEN'));
try {
$apiResponse = $client->crm()->contacts()->basicApi()->getPage(100,true);
return $apiResponse['results'];
} catch (ApiException $e) {
echo "Exception when calling basic_api->get_page: ", $e->getMessage();
}
}
}

Step 5: Create Routes

Next, we will create routes — one for fetching a list of contacts from HubSpot and another to integrate the HubSpot form to create a contact in HubSpot.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| 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!
|
*/

//DISPLAY HUBSPOT USERS
Route::get('/users', [UserController::class, 'displayUser'])->name('display.user');
//HUBSPOT USERS
Route::get('/hubspot-user', [UserController::class, 'userList'])->name('hubspot.user');
//SIGNUP NEWS LETTER To CREATE USER
Route::get('/signup-news', [UserController::class, 'signupUser'])->name('signup.user');

Step 6: Create Blade File

In this step, let’s create home.blade.php (resources/views/home.blade.php)

For layout, use datatable to display records. We have created another view file signup_news.blade.php (resources/views/signup_news.blade.php) for our Hubspot form integration directly on our site.

home.blade.php

<!doctype html>
<html>
<head>
<title>Hubspot User</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--Bootstrap 5 Include -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
<!--Bootstrap Icon -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!--Jquery Include-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!--Datatable Include-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>
</head>
<body>
<div>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/users">Hubspot Integration</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto ml-lg-5 mb-lg-0">
<li class="nav-item p-2 pl-5">
<a class="nav-link active" aria-current="page" href="/users">Home</a>
</li>
<li class="nav-item p-2 pl-5">
<a class="nav-link active" aria-current="page" href="/signup-news">Signup News</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div class="container mt-3">
<table class="table table-responsive table-hover user_datatable">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Created At</th>
<th>Last Modified</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript">
$(function() {
var table = $('.user_datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('hubspot.user') }}",
columns: [{
data: 'id',
name: 'id'
},
{
data: 'first_name',
name: 'first_name'
},
{
data: 'last_name',
name: 'last_name'
},
{
data: 'email',
name: 'email'
},
{
data: 'createdate',
name: 'createdate'
},
{
data: 'lastmodifieddate',
name: 'lastmodifieddate'
}
]
});
});
</script>
</body>
</html>

signup_news.blade.php

Here, you need to embed your Hubspot form script to integrate the form. So when users submit the form, their details will be stored in the contact object. And the workflow that we have created will trigger, sending an email to the user’s provided address.

<!doctype html>
<html>
<head>
<title>Sign Up News</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--Bootstrap 5 Include -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
<!--Bootstrap Icon -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!--Jquery Include-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!--Datatable Include-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>
</head>
<style>
/* Center the form container */
</style>

<body>
<div>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/users">Hubspot Integration</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto ml-lg-5 mb-lg-0">
<li class="nav-item p-2 pl-5">
<a class="nav-link active" aria-current="page" href="/users">Home</a>
</li>
<li class="nav-item p-2 pl-5">
<a class="nav-link active" aria-current="page" href="/signup-news">Signup News</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div id="form-container">
<!-- Embeded Sign Up HubSpot form code here -->

<!-- End Here -->
<div class="container mt-5 text-center">
<span class="h3">Enter Details To Create Contact In Hubspot</span>
<div id="hubspot-form-container"></div>
</div>
</div>
</body>
</html>

8. Testing

Lastly, we have to type the given command and hit enter to run the laravel app:

php artisan serve

Open the web browser, type the given URL, and view the app output

http://127.0.0.1:8000/users

Conclusion

HubSpot and Laravel empower businesses to optimize customer engagement. Integrating HubSpot’s tools like email workflows and contact management with Laravel’s framework, streamlines data collection, personalized communication, and user journey automation. This partnership enhances lead nurturing, strengthens customer bonds, and boosts operational efficiency, leading to substantial business growth.

To stay up-to-date with the latest trends in the development ecosystem, follow Simform Engineering.

--

--