PHPackages                             erikgall/samsara - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. erikgall/samsara

ActiveLibrary[API Development](/categories/api)

erikgall/samsara
================

Laravel SDK for the Samsara Fleet Management API

v1.0.4(2mo ago)2292↓50%MITPHPPHP ^8.1CI passing

Since Apr 7Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/erikgall/samsara)[ Packagist](https://packagist.org/packages/erikgall/samsara)[ RSS](/packages/erikgall-samsara/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (7)Versions (11)Used By (0)

Samsara SDK for Laravel
=======================

[](#samsara-sdk-for-laravel)

A comprehensive Laravel SDK for the [Samsara Fleet Management API](https://developers.samsara.com/). Built with Laravel's HTTP client, this SDK provides a fluent, type-safe interface for all Samsara API endpoints.

Features
--------

[](#features)

- **40+ Resource Endpoints** - Full coverage of Samsara's API including Fleet, Telematics, Safety, Dispatch, Industrial, and more
- **Fluent Query Builder** - Filter, paginate, and stream data with an intuitive query interface
- **Type-Safe Entities** - All API responses are mapped to strongly-typed entity classes
- **Cursor Pagination** - Built-in support for Samsara's cursor-based pagination
- **Lazy Collections** - Memory-efficient streaming for large datasets
- **Webhook Signature Verification** - Middleware for validating incoming Samsara webhook requests
- **Testing Support** - `SamsaraFake` class for easy mocking in tests

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x, 11.x, or 12.x

Installation
------------

[](#installation)

```
composer require erikgall/samsara
```

The package will auto-register its service provider and facade.

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --provider="Samsara\SamsaraServiceProvider"
```

This will create a `config/samsara.php` file where you can configure your API settings.

Configuration
-------------

[](#configuration)

Add your Samsara API token to your `.env` file:

```
SAMSARA_API_KEY=your-api-token-here
SAMSARA_REGION=us  # or 'eu' for European API
SAMSARA_WEBHOOK_SECRET=your-base64-encoded-secret
```

Configuration options in `config/samsara.php`:

```
return [
    'api_key' => env('SAMSARA_API_KEY'),
    'region' => env('SAMSARA_REGION', 'us'),
    'timeout' => env('SAMSARA_TIMEOUT', 30),
    'retry' => env('SAMSARA_RETRY', 3),
    'per_page' => env('SAMSARA_PER_PAGE', 100),
    'webhook_secret' => env('SAMSARA_WEBHOOK_SECRET'),
];
```

Quick Start
-----------

[](#quick-start)

### Using the Facade

[](#using-the-facade)

```
use Samsara\Facades\Samsara;

// Get all drivers
$drivers = Samsara::drivers()->all();

// Find a specific vehicle
$vehicle = Samsara::vehicles()->find('vehicle-id');

// Query with filters
$stats = Samsara::vehicleStats()
    ->current()
    ->whereVehicle(['vehicle-1', 'vehicle-2'])
    ->types(['gps', 'engineStates'])
    ->get();
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use Samsara\Samsara;

class FleetController extends Controller
{
    public function __construct(private Samsara $samsara) {}

    public function drivers()
    {
        return $this->samsara->drivers()->all();
    }
}
```

### Using the Client Directly

[](#using-the-client-directly)

```
use Samsara\Samsara;

$samsara = new Samsara('your-api-token');

// Use EU endpoint
$samsara->useEuEndpoint();

$drivers = $samsara->drivers()->all();
```

Available Resources
-------------------

[](#available-resources)

### Fleet Resources

[](#fleet-resources)

```
// Drivers
$drivers = Samsara::drivers()->all();
$driver = Samsara::drivers()->find('driver-id');
$driver = Samsara::drivers()->create(['name' => 'John Doe', ...]);
$driver = Samsara::drivers()->update('driver-id', ['name' => 'Jane Doe']);
$samsara->drivers()->delete('driver-id');
$samsara->drivers()->activate('driver-id');
$samsara->drivers()->deactivate('driver-id');

// Vehicles
$vehicles = Samsara::vehicles()->all();
$vehicle = Samsara::vehicles()->find('vehicle-id');

// Trailers
$trailers = Samsara::trailers()->all();

// Equipment
$equipment = Samsara::equipment()->all();
```

### Telematics Resources

[](#telematics-resources)

```
// Vehicle Stats (current snapshot)
$stats = Samsara::vehicleStats()
    ->current()
    ->types(['gps', 'fuelPercents', 'engineStates'])
    ->get();

// Vehicle Stats (streaming feed)
$stats = Samsara::vehicleStats()
    ->feed()
    ->types(['gps'])
    ->lazy();

// Vehicle Stats (historical)
$stats = Samsara::vehicleStats()
    ->history()
    ->between($startTime, $endTime)
    ->get();

// Vehicle Locations
$locations = Samsara::vehicleLocations()->current()->get();

// Trips
$trips = Samsara::trips()->query()->get();
```

### Safety Resources

[](#safety-resources)

```
// Hours of Service
$logs = Samsara::hoursOfService()->logs()->get();
$clocks = Samsara::hoursOfService()->clocks()->get();
$violations = Samsara::hoursOfService()->violations()->get();

// Safety Events
$events = Samsara::safetyEvents()->query()->get();

// Maintenance (DVIRs)
$dvirs = Samsara::maintenance()->dvirs()->get();
$defects = Samsara::maintenance()->defects()->get();
```

### Dispatch Resources

[](#dispatch-resources)

```
// Routes
$routes = Samsara::routes()->all();
$route = Samsara::routes()->create([...]);

// Addresses
$addresses = Samsara::addresses()->all();
```

### Organization Resources

[](#organization-resources)

```
// Users
$users = Samsara::users()->all();

// Tags
$tags = Samsara::tags()->all();

// Contacts
$contacts = Samsara::contacts()->all();
```

### Industrial Resources

[](#industrial-resources)

```
// Industrial Assets
$assets = Samsara::industrial()->assets()->get();

// Data Inputs
$inputs = Samsara::industrial()->dataInputs()->get();

// Legacy Sensors (v1 API)
$sensors = Samsara::sensors()->list(['groupId' => 123]);
```

### Integration Resources

[](#integration-resources)

```
// Webhooks
$webhooks = Samsara::webhooks()->all();
$webhook = Samsara::webhooks()->create([
    'name' => 'My Webhook',
    'url' => 'https://example.com/webhook',
    'eventTypes' => ['VehicleLocationUpdated'],
]);

// Gateways
$gateways = Samsara::gateways()->all();

// Live Sharing Links
$shares = Samsara::liveShares()->all();
```

### Additional Resources

[](#additional-resources)

```
// Alerts
Samsara::alerts()->configurations()->get();
Samsara::alerts()->incidents()->get();

// Forms
Samsara::forms()->submissions()->get();
Samsara::forms()->templates();

// Fuel & Energy
Samsara::fuelAndEnergy()->driverEfficiency()->get();

// IFTA Reports
Samsara::ifta()->jurisdictionReport()->get();

// And many more...
```

Query Builder
-------------

[](#query-builder)

The query builder provides a fluent interface for filtering and paginating data:

```
$drivers = Samsara::drivers()
    ->query()
    ->whereTag(['tag-1', 'tag-2'])
    ->updatedAfter(now()->subDays(7))
    ->limit(50)
    ->get();
```

### Available Methods

[](#available-methods)

```
// Filtering
->whereTag($tagIds)
->whereParentTag($parentTagIds)
->whereVehicle($vehicleIds)
->whereDriver($driverIds)
->whereAttribute($attributeValueIds)

// Time Filters
->updatedAfter($datetime)
->createdAfter($datetime)
->startTime($datetime)
->endTime($datetime)
->between($start, $end)

// Stats Types
->types(['gps', 'engineStates', 'fuelPercents'])
->withDecorations(['reverseGeo'])

// Pagination
->limit(100)
->after($cursor)

// Expand Related Data
->expand(['driver', 'vehicle'])

// Custom Filters
->where('status', 'active')
```

### Execution Methods

[](#execution-methods)

```
// Get results as EntityCollection
$results = $query->get();

// Get first result
$first = $query->first();

// Paginate with cursor
$paginator = $query->paginate(100);

// Lazy stream (memory efficient)
$lazy = $query->lazy(100);
```

### Cursor Pagination

[](#cursor-pagination)

```
$paginator = Samsara::drivers()->query()->paginate(50);

foreach ($paginator as $driver) {
    // Process driver
}

while ($paginator->hasMorePages()) {
    $paginator = $paginator->nextPage();

    foreach ($paginator as $driver) {
        // Process next page
    }
}
```

### Lazy Collections

[](#lazy-collections)

For large datasets, use lazy collections to stream results:

```
$drivers = Samsara::drivers()
    ->query()
    ->lazy(100) // Fetch 100 at a time
    ->filter(fn ($driver) => $driver->isActive())
    ->take(500);

foreach ($drivers as $driver) {
    // Memory-efficient processing
}
```

Entities
--------

[](#entities)

All API responses are mapped to entity classes that extend `Illuminate\Support\Fluent`:

```
$driver = Samsara::drivers()->find('driver-id');

// Access properties
$driver->id;
$driver->name;
$driver->phone;

// Check status
$driver->isActive();
$driver->isDeactivated();

// Convert to array
$driver->toArray();

// Convert to JSON
$driver->toJson();
```

### Entity Collections

[](#entity-collections)

```
$drivers = Samsara::drivers()->all();

// Find by ID
$driver = $drivers->findById('driver-123');

// Get all IDs
$ids = $drivers->ids();

// All Laravel Collection methods work
$activeDrivers = $drivers->filter(fn ($d) => $d->isActive());
```

Error Handling
--------------

[](#error-handling)

The SDK throws specific exceptions for different error types:

```
use Samsara\Exceptions\AuthenticationException;
use Samsara\Exceptions\AuthorizationException;
use Samsara\Exceptions\NotFoundException;
use Samsara\Exceptions\ValidationException;
use Samsara\Exceptions\RateLimitException;
use Samsara\Exceptions\ServerException;

try {
    $driver = Samsara::drivers()->find('invalid-id');
} catch (NotFoundException $e) {
    // Handle 404
} catch (RateLimitException $e) {
    $retryAfter = $e->getRetryAfter();
    // Handle rate limiting
} catch (ValidationException $e) {
    $errors = $e->getErrors();
    // Handle validation errors
}
```

Webhook Signature Verification
------------------------------

[](#webhook-signature-verification)

The SDK includes middleware to verify that incoming webhook requests are authentic. It validates the HMAC-SHA256 signature sent in the `X-Samsara-Signature` header.

```
use Samsara\Webhooks\VerifyWebhookSignature;

Route::post('/samsara/webhook', WebhookController::class)
    ->middleware(VerifyWebhookSignature::class);
```

The middleware uses the `webhook_secret` from your `config/samsara.php` by default. You can also pass a custom secret and tolerance (in seconds) as middleware parameters:

```
Route::post('/samsara/webhook', WebhookController::class)
    ->middleware('samsara.webhook:my-secret-key,600');
```

For detailed usage, custom secrets, and controller examples, see the [Webhooks documentation](docs/resources/webhooks.md).

Testing
-------

[](#testing)

The SDK includes a `SamsaraFake` class for testing:

```
use Samsara\Testing\SamsaraFake;

public function test_it_fetches_drivers(): void
{
    $fake = SamsaraFake::create();

    $fake->fakeDrivers([
        ['id' => 'driver-1', 'name' => 'John Doe'],
        ['id' => 'driver-2', 'name' => 'Jane Doe'],
    ]);

    $drivers = $fake->drivers()->all();

    $this->assertCount(2, $drivers);
    $fake->assertRequested('/fleet/drivers');
}
```

### Using Test Fixtures

[](#using-test-fixtures)

```
use Samsara\Testing\Fixtures;

$driversData = Fixtures::drivers();
$vehiclesData = Fixtures::vehicles();
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Credits
-------

[](#credits)

- [Erik Galloway](https://github.com/erikgall)

###  Health Score

45

—

FairBetter than 92% of packages

Maintenance91

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~36 days

Recently: every ~9 days

Total

10

Last Release

72d ago

Major Versions

v0.4.0 → v1.x-dev2026-01-18

### Community

Maintainers

![](https://www.gravatar.com/avatar/44d0a5db4aa44c040bcdd2d07a5a4e894f02fc08a11140e2282ac7d080d113f6?d=identicon)[erikgall](/maintainers/erikgall)

---

Top Contributors

[![erikgall](https://avatars.githubusercontent.com/u/8866568?v=4)](https://github.com/erikgall "erikgall (74 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/erikgall-samsara/health.svg)

```
[![Health](https://phpackages.com/badges/erikgall-samsara/health.svg)](https://phpackages.com/packages/erikgall-samsara)
```

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M219](/packages/spatie-laravel-query-builder)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[esign/laravel-conversions-api

A laravel wrapper package around the Facebook Conversions API

69145.4k](/packages/esign-laravel-conversions-api)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
