Associations
Associations represent the relationships between HubSpot CRM objects, such as contacts linked to companies or deals linked to line items. Laravel HubSpot provides an Eloquent-style API for managing these relationships.
Accessing Associated Records
Association methods are defined on each model and return an Association instance:
php
use Rollogi\LaravelHubspot\Crm\Contact;
$contact = Contact::findOrFail('123');
// Get all associated companies
$companies = $contact->companies()->get();
// Access via magic property (returns the collection)
$companies = $contact->companies;
// Access singular (returns first associated record)
$company = $contact->company;Eager Loading
Include associations in the initial query to avoid N+1 requests:
php
use Rollogi\LaravelHubspot\Crm\Contact;
$contacts = Contact::query()
->with(['companies', 'deals'])
->get();Creating Associations
php
use Rollogi\LaravelHubspot\Crm\Contact;
$contact = Contact::findOrFail('123');
// Attach an existing company
$contact->companies()->attach('456');
$contact->companies()->attach($companyModel);
// Create a new company and automatically associate it
$company = $contact->companies()->create([
'name' => 'Acme Corp',
'domain' => 'acme.com',
]);Detaching
php
use Rollogi\LaravelHubspot\Crm\Contact;
$contact = Contact::findOrFail('123');
// Detach specific associations
$contact->companies()->detach('456');
$contact->companies()->detach(['456', '789']);
$contact->companies()->detach($companyModel);
// Detach all associations
$contact->companies()->detach();Syncing
Sync brings the association set to exactly the IDs you provide, attaching missing ones and detaching extras using minimum API calls.
sync
php
use Rollogi\LaravelHubspot\Crm\Contact;
$contact = Contact::findOrFail('123');
// Sync to exactly these companies (attach new, detach removed)
$changes = $contact->companies()->sync(['456', '789', '012']);
// Returns: ['attached' => ['789', '012'], 'detached' => ['old-id']]syncWithoutDetaching
php
// Sync without detaching (only attach missing)
$changes = $contact->companies()->syncWithoutDetaching(['456', '789']);
// Returns: ['attached' => ['789']]toggle
php
// Toggle — attached become detached, detached become attached
$changes = $contact->companies()->toggle(['456', '789']);
// Returns: ['attached' => [...], 'detached' => [...]]All sync operations accept IDs as strings, integers, or Model instances. They use HubSpot's v4 batch endpoints and automatically chunk at 100 per request.
Getting Current Association IDs
Retrieve the current associated IDs without hydrating full models:
php
$ids = $contact->companies()->currentIds(); // Illuminate\Support\Collection of string IDs