### Samsara SDK Query Builder Examples Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Demonstrates advanced usage of the Samsara SDK's fluent query builder. Examples include filtering drivers by tags, performing time-based queries for vehicle stats, paginating vehicles, and lazily loading large datasets. ```php use Samsara\Facades\Samsara; // Filter by tags $drivers = Samsara::drivers() ->query() ->whereTag('tag-123') ->get(); // Time-based queries $stats = Samsara::vehicleStats() ->between('2024-01-01', '2024-01-31') ->types(['gps', 'fuelPercents']) ->get(); // Pagination $vehicles = Samsara::vehicles() ->query() ->limit(50) ->paginate(); // Lazy loading for large datasets Samsara::vehicleStats() ->types(['gps']) ->lazy() ->each(function ($stat) { // Process each stat }); ``` -------------------------------- ### Basic Usage of Samsara SDK Facade Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Demonstrates basic usage of the Samsara SDK using its facade. It shows how to retrieve all drivers, find a specific vehicle by ID, and get vehicle statistics with specified types. ```php use Samsara\Facades\Samsara; // Get all drivers $drivers = Samsara::drivers()->all(); // Find a specific vehicle $vehicle = Samsara::vehicles()->find('vehicle-id'); // Get vehicle stats $stats = Samsara::vehicleStats() ->types(['gps', 'engineStates']) ->get(); ``` -------------------------------- ### Install Samsara SDK using Composer Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Installs the Samsara SDK package for Laravel using Composer. This command fetches and installs the latest version of the package, automatically registering its service provider and facade. ```bash composer require erikgall/samsara ``` -------------------------------- ### Creating a Fresh Samsara SDK Instance Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Shows how to create a fresh instance of the Samsara SDK by passing the API token directly to the `make` method. This is useful when you need to instantiate the SDK outside of Laravel's service container. ```php use Samsara\Samsara; $samsara = Samsara::make('your-api-token'); $drivers = $samsara->drivers()->all(); ``` -------------------------------- ### Complete Example: Fleet Overview (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/query-builder.md A practical example demonstrating how to retrieve all active drivers with their associated tags and how to fetch vehicles filtered by a specific tag. This combines multiple query builder methods. ```php // Get all active drivers with their tags $drivers = Samsara::drivers() ->active() ->get(); // Get vehicles by tag $vehicles = Samsara::vehicles() ->query() ->whereTag('fleet-a') ->get(); ``` -------------------------------- ### Testing with SamsaraFake Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Demonstrates how to use `SamsaraFake` to mock API responses for testing purposes. This allows you to simulate API behavior, such as returning specific driver data, and assert the results in your tests. ```php use Samsara\Facades\Samsara; public function test_it_lists_drivers(): void { $fake = Samsara::fake(); $fake->fakeDrivers([ ['id' => 'driver-1', 'name' => 'John Doe'], ['id' => 'driver-2', 'name' => 'Jane Smith'], ]); $drivers = $fake->drivers()->all(); $this->assertCount(2, $drivers); $this->assertSame('John Doe', $drivers[0]->name); } ``` -------------------------------- ### Complete Example: Hours of Service (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/query-builder.md Provides examples for retrieving Hours of Service (HOS) data, including logs for specific drivers within a date range and current HOS clock status for a driver. This demonstrates specialized resource querying. ```php // Get HOS logs for specific drivers $logs = Samsara::hoursOfService() ->logs() ->whereDriver(['driver-1', 'driver-2']) ->between($startOfWeek, $endOfWeek) ->get(); // Get current HOS clocks $clocks = Samsara::hoursOfService() ->clocks() ->whereDriver('driver-1') ->get(); ``` -------------------------------- ### Install and Configure Samsara SDK for Laravel Source: https://context7.com/erikgall/samsara/llms.txt Instructions for installing the Samsara SDK via Composer and publishing its configuration file. It also shows how to configure API credentials and settings in the .env file and the samsara.php configuration file. ```bash # Install via Composer composer require erikgall/samsara # Publish configuration file php artisan vendor:publish --provider="Samsara\SamsaraServiceProvider" ``` ```env # .env configuration SAMSARA_API_KEY=samsara_api_xxxxxxxxxxxxxxxx SAMSARA_REGION=us SAMSARA_TIMEOUT=30 SAMSARA_RETRY=3 SAMSARA_PER_PAGE=100 ``` ```php // config/samsara.php return [ 'api_key' => env('SAMSARA_API_KEY'), 'region' => env('SAMSARA_REGION', 'us'), // 'us' or 'eu' 'timeout' => env('SAMSARA_TIMEOUT', 30), 'retry' => env('SAMSARA_RETRY', 3), 'per_page' => env('SAMSARA_PER_PAGE', 100), ]; ``` -------------------------------- ### Samsara SDK Exception Handling Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Provides examples of how to handle specific exceptions thrown by the Samsara SDK. It covers `AuthenticationException`, `NotFoundException`, `RateLimitException`, and `ValidationException`, showing how to catch them and access relevant information like retry-after times or validation errors. ```php use Samsara\Facades\Samsara; use Samsara\Exceptions\AuthenticationException; use Samsara\Exceptions\NotFoundException; use Samsara\Exceptions\RateLimitException; use Samsara\Exceptions\ValidationException; try { $driver = Samsara::drivers()->find('driver-id'); } catch (AuthenticationException $e) { // Invalid API token (401) } catch (NotFoundException $e) { // Resource not found (404) } catch (RateLimitException $e) { // Rate limited (429) $retryAfter = $e->getRetryAfter(); } catch (ValidationException $e) { // Validation errors (422) $errors = $e->getErrors(); } ``` -------------------------------- ### Complete Example: Vehicle Telemetry (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/query-builder.md Shows a comprehensive example for retrieving vehicle telemetry data, including specific stat types, filtering by vehicle IDs, defining a time range, and including address decorations. This illustrates a complex data retrieval scenario. ```php use Carbon\Carbon; // Get GPS and fuel data for the last 24 hours $stats = Samsara::vehicleStats() ->types(['gps', 'fuelPercents', 'engineStates']) ->whereVehicle(['vehicle-1', 'vehicle-2']) ->between(Carbon::now()->subDay(), Carbon::now()) ->withDecorations(['address']) ->get(); ``` -------------------------------- ### PHPUnit Trait for Samsara Fake Setup Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md A reusable PHPUnit trait that simplifies the setup of the Samsara fake client in tests. It provides a `setUpSamsara` method to initialize the fake client and makes it available as a protected property. ```php samsara = Samsara::fake(); } } ``` -------------------------------- ### Publish Samsara Configuration Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Publishes the Samsara configuration file to your Laravel project. This command makes the `config/samsara.php` file available for customization, allowing you to adjust SDK settings. ```bash php artisan vendor:publish --provider="Samsara\SamsaraServiceProvider" ``` -------------------------------- ### Configuring Pagination for Results (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/query-builder.md Details how to control the number of results returned per page using `limit` or `take`, and how to implement cursor-based pagination to navigate through large datasets. Includes examples for getting the next page and iterating. ```php // Limit to 50 results ->limit(50) // Alias for limit ->take(50) ``` ```php // Get first page $paginator = Samsara::vehicles() ->query() ->limit(50) ->paginate(); // Iterate through items foreach ($paginator as $vehicle) { echo $vehicle->name; } // Get next page if ($paginator->hasMorePages()) { $nextPage = $paginator->nextPage(); } ``` ```php // Start after a specific cursor ->after('cursor-token-from-previous-response') ``` -------------------------------- ### Complete Fleet Service Test Example in PHP Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md Provides a comprehensive example of testing fleet-related API interactions. It includes tests for listing active drivers, finding a driver by ID, and handling cases where a driver is not found. ```php fakeDrivers([ ['id' => 'driver-1', 'name' => 'John', 'driverActivationStatus' => 'active'], ['id' => 'driver-2', 'name' => 'Jane', 'driverActivationStatus' => 'deactivated'], ]); $drivers = $fake->drivers()->all(); $this->assertCount(2, $drivers); $this->assertInstanceOf(Driver::class, $drivers[0]); } public function test_it_can_find_driver_by_id(): void { $fake = Samsara::fake(); $fake->fakeResponse('/fleet/drivers/driver-1', [ 'id' => 'driver-1', 'name' => 'John Doe', ]); $driver = $fake->drivers()->find('driver-1'); $this->assertNotNull($driver); $this->assertSame('John Doe', $driver->name); } public function test_it_returns_null_for_missing_driver(): void { $fake = Samsara::fake(); $fake->fakeResponse('/fleet/drivers/invalid', [], 404); $driver = $fake->drivers()->find('invalid'); $this->assertNull($driver); } } ``` -------------------------------- ### Manage Samsara Drivers using the SDK Source: https://context7.com/erikgall/samsara/llms.txt Provides examples for performing CRUD operations on driver resources, including getting all drivers, finding a specific driver, creating, updating, and deleting drivers. It also covers activation/deactivation, finding by external ID, and remote sign-out. ```php use Samsara\Facades\Samsara; // Get all drivers $drivers = Samsara::drivers()->all(); // Find a specific driver $driver = Samsara::drivers()->find('driver-id'); // Create a new driver $driver = Samsara::drivers()->create([ 'name' => 'John Doe', 'phone' => '+1234567890', 'licenseNumber' => 'DL123456', 'licenseState' => 'CA', 'timezone' => 'America/Los_Angeles', ]); // Update a driver $driver = Samsara::drivers()->update('driver-id', [ 'phone' => '+0987654321', ]); // Delete a driver Samsara::drivers()->delete('driver-id'); // Activate/Deactivate drivers Samsara::drivers()->activate('driver-id'); Samsara::drivers()->deactivate('driver-id'); // Find by external ID $driver = Samsara::drivers()->findByExternalId('payroll_id', '12345'); // Remote sign out Samsara::drivers()->remoteSignOut('driver-id'); // Driver entity helper methods $driver = Samsara::drivers()->find('driver-id'); $driver->isActive(); // bool $driver->isDeactivated(); // bool $driver->getDisplayName(); // string $driver->isEldExempt(); // bool $driver->getTagIds(); // array $driver->getExternalId('payroll_id'); // ?string ``` -------------------------------- ### Example Webhook Handler (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/webhooks.md A comprehensive example of a PHP webhook handler controller. It demonstrates how to receive and process different event types from Samsara using a `match` statement, including specific methods for handling vehicle location, HOS logs, and safety events. ```php input('eventType'); $data = $request->input('data'); match ($eventType) { 'VehicleLocation' => $this->handleVehicleLocation($data), 'DriverHosLog' => $this->handleDriverHosLog($data), 'SafetyEvent' => $this->handleSafetyEvent($data), default => null, }; return response()->json(['status' => 'ok']); } protected function handleVehicleLocation(array $data): void { // Process vehicle location update } protected function handleDriverHosLog(array $data): void { // Process HOS log update } protected function handleSafetyEvent(array $data): void { // Process safety event } } ``` -------------------------------- ### Quick Example: Fetching Samsara API Data with Laravel SDK Source: https://github.com/erikgall/samsara/blob/main/docs/index.md This PHP code snippet demonstrates how to use the Samsara SDK for Laravel to interact with the Samsara Fleet Management API. It shows examples of fetching all drivers, finding a specific vehicle by ID, and querying vehicle statistics with filters for specific vehicles and data types. The SDK utilizes a fluent query builder for intuitive data retrieval. ```php 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(); ``` -------------------------------- ### PHPUnit Unit Test Example Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md An example of a PHPUnit unit test for parsing driver log responses. This test focuses on the logic within a specific class without external dependencies. It uses the `#[Test]` attribute and asserts the expected output. ```php use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class SamsaraClientTest extends TestCase { #[Test] public function it_parses_driver_log_response_correctly(): void { $client = new SamsaraClient('test-api-key'); $response = ['driver_id' => '123', 'status' => 'ON_DUTY']; $result = $client->parseDriverLog($response); $this->assertEquals('123', $result->driverId); $this->assertEquals(DriverStatus::ON_DUTY, $result->status); } } ``` -------------------------------- ### Faking Samsara Resource Responses (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md Provides examples of how to use SamsaraFake to mock responses for various Samsara resources including drivers, vehicles, and vehicle stats. Each example shows the structure of the data to be faked. ```php $fake->fakeDrivers([ [ 'id' => 'driver-1', 'name' => 'John Doe', 'phone' => '+1234567890', 'driverActivationStatus' => 'active', ], ]); ``` ```php $fake->fakeVehicles([ [ 'id' => 'vehicle-1', 'name' => 'Truck 001', 'vin' => '1HGBH41JXMN109186', 'make' => 'Ford', 'model' => 'F-150', ], ]); ``` ```php $fake->fakeVehicleStats([ [ 'id' => 'vehicle-1', 'name' => 'Truck 001', 'gps' => [ 'latitude' => 37.7749, 'longitude' => -122.4194, 'time' => '2024-01-15T10:00:00Z', ], 'engineState' => [ 'value' => 'On', 'time' => '2024-01-15T10:00:00Z', ], ], ]); ``` -------------------------------- ### Basic Usage of Samsara SDK with Dependency Injection Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Illustrates how to use the Samsara SDK within a Laravel controller using dependency injection. The `Samsara` class is injected into the controller's constructor, allowing access to its methods. ```php use Samsara\Samsara; class FleetController extends Controller { public function __construct( protected Samsara $samsara ) {} public function index() { return $this->samsara->drivers()->all(); } } ``` -------------------------------- ### PHP PHPDoc Class and Property Documentation Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md Provides examples of PHPDoc standards for class-level documentation and property type declarations. Emphasizes conciseness and specificity in documentation. ```php /** * Samsara ELD API client. * * @author Your Name */ class SamsaraClient /** * The API endpoints configuration. * * @var array */ protected array $endpoints; ``` -------------------------------- ### Complete Samsara Configuration File (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/configuration.md Provides a complete example of the `config/samsara.php` file, illustrating all available configuration options and their default values. This file is generated after publishing the vendor configuration. ```php API Tokens. | */ 'api_key' => env('SAMSARA_API_KEY'), /* |-------------------------------------------------------------------------- | API Region |-------------------------------------------------------------------------- | | The region for your Samsara account. Use 'us' for United States or | 'eu' for European Union customers. | */ 'region' => env('SAMSARA_REGION', 'us'), /* |-------------------------------------------------------------------------- | Request Timeout |-------------------------------------------------------------------------- | | The number of seconds to wait before timing out a request. | */ 'timeout' => env('SAMSARA_TIMEOUT', 30), /* |-------------------------------------------------------------------------- | Retry Count |-------------------------------------------------------------------------- | | The number of times to retry a failed request before giving up. | */ 'retry' => env('SAMSARA_RETRY', 3), /* |-------------------------------------------------------------------------- | Items Per Page |-------------------------------------------------------------------------- | | The default number of items to fetch per page for paginated requests. | */ 'per_page' => env('SAMSARA_PER_PAGE', 100), ]; ``` -------------------------------- ### PHPUnit Feature/Integration Test Example Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md An example of a PHPUnit feature/integration test for fetching driver logs from an API. This test mocks HTTP responses using `Http::fake` to simulate external API calls. It verifies that the service interacts correctly with the mocked API. ```php use PHPUnit\Framework\Attributes\Test; use Illuminate\Support\Facades\Http; class EldServiceTest extends TestCase { #[Test] public function it_fetches_driver_logs_from_api(): void { Http::fake([ 'api.samsara.com/*' => Http::response(['data' => [...]], 200) ]); $service = app(EldService::class); $logs = $service->fetchDriverLogs('driver-123'); $this->assertNotEmpty($logs); Http::assertSent(function ($request) { return $request->url() === 'https://api.samsara.com/v1/driver-logs/driver-123'; }); } } ``` -------------------------------- ### Samsara Dispatch Resource Operations (PHP) Source: https://github.com/erikgall/samsara/blob/main/README.md Provides examples for managing dispatch resources, including retrieving all routes and creating new routes. ```php // Routes $routes = Samsara::routes()->all(); $route = Samsara::routes()->create([...]); // Addresses $addresses = Samsara::addresses()->all(); ``` -------------------------------- ### Environment-Specific Samsara Configuration (Production) Source: https://github.com/erikgall/samsara/blob/main/docs/configuration.md Shows an example of environment-specific configuration for production, setting the API key, timeout, and retry count. This configuration is usually loaded from files like `.env.production`. ```env # .env.production SAMSARA_API_KEY=samsara_api_prod_token SAMSARA_TIMEOUT=30 SAMSARA_RETRY=3 ``` -------------------------------- ### Handling ServerException in PHP Source: https://github.com/erikgall/samsara/blob/main/docs/error-handling.md Illustrates how to catch `ServerException` in PHP, which is thrown for server-side errors (HTTP 5xx). The example suggests logging the critical error and its details. ```php use Samsara\Facades\Samsara; use Samsara\Exceptions\ServerException; try { $drivers = Samsara::drivers()->all(); } catch (ServerException $e) { // Log and alert, likely a temporary issue Log::critical('Samsara API is down', [ 'message' => $e->getMessage(), 'code' => $e->getCode(), ]); } ``` -------------------------------- ### Samsara Fleet Resource Operations (PHP) Source: https://github.com/erikgall/samsara/blob/main/README.md Provides examples of common operations for Fleet resources like drivers, vehicles, trailers, and equipment. Includes creating, finding, updating, and deleting drivers. ```php // 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(); ``` -------------------------------- ### Testing Samsara SDK Error Handling (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md Provides examples of how to test error handling scenarios for the Samsara SDK, specifically focusing on authentication and validation errors. It demonstrates how to expect specific exceptions and inspect their details. ```php use Samsara\Exceptions\AuthenticationException; public function test_handles_auth_error(): void { $fake = Samsara::fake(); $fake->fakeResponse('/fleet/drivers', [ 'message' => 'Invalid API token', ], 401); $this->expectException(AuthenticationException::class); $fake->drivers()->all(); } ``` ```php use Samsara\Exceptions\ValidationException; public function test_handles_validation_error(): void { $fake = Samsara::fake(); $fake->fakeResponse('/fleet/drivers', [ 'message' => 'Validation failed', 'errors' => ['name' => ['Name is required']], ], 422); try { $fake->drivers()->create([]); } catch (ValidationException $e) { $this->assertArrayHasKey('name', $e->getErrors()); } } ``` -------------------------------- ### Handling Samsara API Exceptions Source: https://github.com/erikgall/samsara/blob/main/README.md Provides examples of how to catch specific exceptions thrown by the Samsara SDK for various error conditions. This includes `NotFoundException`, `RateLimitException` (with retry information), and `ValidationException` (with error details). ```php 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 } ``` -------------------------------- ### Get Driver Files History (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/tachograph.md Retrieves a history of driver files within a specified date range. Uses the Samsara facade and Carbon for date handling. Returns an array of driver file records. ```php // Get driver files history $driverFiles = Samsara::tachograph() ->driverFilesHistory() ->between(now()->subDays(30), now()) ->get(); ``` -------------------------------- ### Usage of Samsara Fake Trait in PHP Test Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md Demonstrates how to use the `UsesSamsaraFake` trait within a PHPUnit test class. It shows the inclusion of the trait and the necessary call to `setUpSamsara` within the test's `setUp` method. ```php class MyTest extends TestCase { use UsesSamsaraFake; protected function setUp(): void { parent::setUp(); $this->setUpSamsara(); } public function test_example(): void { $this->samsara->fakeDrivers([/* ... */]); // ... } } ``` -------------------------------- ### Get All Vehicle Locations (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/vehicle-locations.md Retrieves the current locations for all vehicles in the fleet. This is a basic usage example for fetching all available vehicle location data. ```php use Samsara\Facades\Samsara; // Get current locations for all vehicles $locations = Samsara::vehicleLocations()->all(); ``` -------------------------------- ### Basic SamsaraFake Client Creation and Usage (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md Demonstrates how to create a fake Samsara client using `Samsara::fake()` and mock responses for the drivers endpoint. It shows how to fake driver data and then retrieve and assert on it. ```php use Samsara\Facades\Samsara; use Samsara\Testing\SamsaraFake; public function test_it_lists_drivers(): void { $fake = Samsara::fake(); $fake->fakeDrivers([ ['id' => 'driver-1', 'name' => 'John Doe'], ['id' => 'driver-2', 'name' => 'Jane Smith'], ]); $drivers = $fake->drivers()->all(); $this->assertCount(2, $drivers); $this->assertSame('John Doe', $drivers[0]->name); } ``` -------------------------------- ### Get HOS Data (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/hours-of-service.md Retrieve Hours of Service (HOS) logs, clocks, and violations using the Samsara API. This basic usage example demonstrates how to fetch all records for each category. ```php use Samsara\Facades\Samsara; // Get HOS logs $logs = Samsara::hoursOfService()->logs()->get(); // Get HOS clocks $clocks = Samsara::hoursOfService()->clocks()->get(); // Get HOS violations $violations = Samsara::hoursOfService()->violations()->get(); // Get daily logs $dailyLogs = Samsara::hoursOfService()->dailyLogs()->get(); ``` -------------------------------- ### Get and Find Gateways (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/gateways.md Demonstrates how to retrieve all gateway devices or find a specific gateway by its ID using the Samsara PHP SDK. This requires the Samsara SDK to be installed and configured. ```php use Samsara\Facades\Samsara; // Get all gateways $gateways = Samsara::gateways()->all(); // Find a gateway $gateway = Samsara::gateways()->find('gateway-id'); ``` -------------------------------- ### Build Queries with Fluent Interface Source: https://github.com/erikgall/samsara/blob/main/README.md Demonstrates the use of the Samsara SDK's query builder for filtering and paginating data. This example shows how to retrieve drivers based on tags, update time, and a specific limit, showcasing the fluent interface. ```php $drivers = Samsara::drivers() ->query() ->whereTag(['tag-1', 'tag-2']) ->updatedAfter(now()->subDays(7)) ->limit(50) ->get(); ``` -------------------------------- ### Configure Samsara API Key and Region Source: https://github.com/erikgall/samsara/blob/main/docs/getting-started.md Sets the Samsara API key and optionally the region in the `.env` file. The `SAMSARA_API_KEY` is required for authentication, while `SAMSARA_REGION` can be set to 'eu' for European customers. ```env SAMSARA_API_KEY=your-api-token-here SAMSARA_REGION=eu ``` -------------------------------- ### Cursor Pagination with Samsara SDK Source: https://github.com/erikgall/samsara/blob/main/README.md Illustrates how to implement cursor-based pagination using the Samsara SDK. This example shows fetching an initial paginated set of drivers and iterating through subsequent pages using `hasMorePages()` and `nextPage()`. ```php $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 } } ``` -------------------------------- ### PHP Early Return Example Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md Demonstrates the use of early returns in PHP to avoid nested if-else statements, improving code readability and maintainability. This pattern is preferred over traditional else blocks. ```php // GOOD if (! $condition) { return; } // Continue with main logic // BAD - Don't do this if ($condition) { // logic } else { return; } ``` -------------------------------- ### Code Commenting Best Practices Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md Provides guidelines for writing effective code comments. It shows examples of when to use comments, such as converting timestamps, documenting rate limits, and mapping status codes. Avoid commenting obvious code, writing lengthy explanations, or leaving commented-out code. ```php // Convert API timestamp to Carbon instance $timestamp = Carbon::createFromTimestamp($data['timestamp']); // API rate limit: 100 requests per minute $this->rateLimiter->throttle(100, 60); // Map API status codes to internal enum values return match ($apiStatus) { ... }; ``` -------------------------------- ### Instantiate and Use Samsara Client Directly Source: https://github.com/erikgall/samsara/blob/main/README.md Illustrates creating a Samsara client instance directly with an API token and optionally configuring it to use the EU endpoint before making API calls. ```php use Samsara\Samsara; $samsara = new Samsara('your-api-token'); // Use EU endpoint $samsara->useEuEndpoint(); $drivers = $samsara->drivers()->all(); ``` -------------------------------- ### Testing Samsara API Calls with SamsaraFake Source: https://github.com/erikgall/samsara/blob/main/README.md Demonstrates how to use the `SamsaraFake` class for unit testing interactions with the Samsara API. This example shows how to fake driver data, retrieve it using the fake client, and assert that the correct API endpoint was requested. ```php 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'); } ``` -------------------------------- ### Utilizing Test Fixtures in Samsara SDK Source: https://github.com/erikgall/samsara/blob/main/README.md Shows how to use predefined test fixtures provided by the Samsara SDK for easily obtaining mock data. This example demonstrates loading fixture data for drivers and vehicles. ```php use Samsara\Testing\Fixtures; $driversData = Fixtures::drivers(); $vehiclesData = Fixtures::vehicles(); ``` -------------------------------- ### Use Samsara SDK via Facade or Dependency Injection in Laravel Source: https://context7.com/erikgall/samsara/llms.txt Demonstrates how to access the Samsara SDK functionalities using either the Samsara facade or through dependency injection in Laravel controllers. It also shows how to create a fresh SDK instance with custom configurations and switch API regions. ```php use Samsara\Facades\Samsara; use Samsara\Samsara; // Using the Facade $drivers = Samsara::drivers()->all(); $vehicle = Samsara::vehicles()->find('vehicle-id'); // Using Dependency Injection class FleetController extends Controller { public function __construct(protected Samsara $samsara) {} public function index() { return $this->samsara->drivers()->all(); } } // Creating a fresh instance with custom configuration $samsara = Samsara::make('your-api-token', [ 'timeout' => 60, 'retry' => 5, ]); $samsara->useEuEndpoint(); // Switch to EU region $drivers = $samsara->drivers()->all(); ``` -------------------------------- ### PHP Method Naming Conventions Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md Illustrates recommended naming conventions for PHP methods, categorizing them into boolean checkers, getters, setters (fluent), and actions. This promotes consistency across the codebase. ```php // Boolean Checkers public function isConnected(): bool public function hasValidCredentials(): bool public function canFetchLogs(): bool // Getters public function getDriverLogs(): array public function getHosData(): HosData // Setters (fluent) public function setApiKey(string $apiKey): self public function setTimeout(int $seconds): self // Actions public function connect(): void public function fetchLogs(): LogCollection public function syncData(): bool ``` -------------------------------- ### Loading and Using Samsara SDK Fixtures (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/testing.md Shows how to load pre-defined JSON fixtures for common Samsara API responses using the `Fixtures` class. It lists available fixtures and demonstrates using them with SamsaraFake. ```php use Samsara\Testing\Fixtures; // Load driver fixtures $drivers = Fixtures::drivers(); // Load vehicle fixtures $vehicles = Fixtures::vehicles(); // Load vehicle stats fixtures $stats = Fixtures::vehicleStats(); ``` ```php use Samsara\Facades\Samsara; use Samsara\Testing\Fixtures; public function test_with_fixtures(): void { $fake = Samsara::fake(); $fake->fakeDrivers(Fixtures::drivers()); $drivers = $fake->drivers()->all(); $this->assertNotEmpty($drivers); } ``` -------------------------------- ### Get All Safety Events Source: https://github.com/erikgall/samsara/blob/main/docs/resources/safety-events.md Retrieves a list of all safety events. ```APIDOC ## GET /resources/safety-events ### Description Retrieves a list of all safety events recorded by the Samsara system. ### Method GET ### Endpoint /resources/safety-events ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of results to return. - **after** (string) - Optional - The cursor for the next page of results. ### Response #### Success Response (200) - **data** (array) - An array of safety event objects. - **id** (string) - Safety event ID - **driverId** (string) - Driver ID - **vehicleId** (string) - Vehicle ID - **eventType** (string) - Type of safety event - **time** (string) - Event timestamp (ISO 8601) - **location** (object) - Event location - **behaviorLabel** (string) - Behavior classification - **maxSpeedMph** (float) - Maximum speed during event - **durationMs** (int) - Event duration in milliseconds - **coachingState** (string) - Coaching status #### Response Example ```json { "data": [ { "id": "event-123", "driverId": "driver-456", "vehicleId": "vehicle-789", "eventType": "harshBrake", "time": "2023-10-27T10:00:00Z", "location": { "latitude": 37.7749, "longitude": -122.4194 }, "behaviorLabel": "Aggressive Driving", "maxSpeedMph": 55.5, "durationMs": 1500, "coachingState": "triggered" } ], "pagination": { "next_cursor": "some_cursor" } } ``` ``` -------------------------------- ### Manage Webhooks, Gateways, and Live Sharing Links Source: https://github.com/erikgall/samsara/blob/main/README.md This snippet demonstrates how to interact with Samsara's Webhooks, Gateways, and Live Sharing Links resources. It covers fetching all existing resources and creating new webhooks with specified event types. ```php // 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(); ``` -------------------------------- ### Get Safety Event Audit Logs Source: https://github.com/erikgall/samsara/blob/main/docs/resources/safety-events.md Retrieves audit logs for safety events, allowing tracking of changes and reviews. ```APIDOC ## GET /resources/safety-events/audit-logs ### Description Retrieves a feed of audit logs for safety events, detailing changes and reviews. ### Method GET ### Endpoint /resources/safety-events/audit-logs ### Parameters #### Query Parameters - **between** (string) - Optional - A date range in 'YYYY-MM-DD' format, separated by a comma (e.g., '2023-10-20,2023-10-27'). ### Response #### Success Response (200) - **data** (array) - An array of audit log objects. - **id** (string) - Audit log ID - **eventId** (string) - Associated safety event ID - **userId** (string) - User who performed the action - **action** (string) - The action performed (e.g., 'reviewed', 'commented') - **timestamp** (string) - Timestamp of the action (ISO 8601) #### Response Example ```json { "data": [ { "id": "audit-log-1", "eventId": "event-123", "userId": "user-abc", "action": "reviewed", "timestamp": "2023-10-27T11:00:00Z" } ], "pagination": { "next_cursor": "some_cursor" } } ``` ``` -------------------------------- ### Get All DVIRs Source: https://github.com/erikgall/samsara/blob/main/docs/resources/maintenance.md Retrieves all Driver Vehicle Inspection Reports (DVIRs) associated with the fleet. This is a basic entry point for accessing maintenance data. ```php use Samsara\Facades\Samsara; // Get all DVIRs $dvirs = Samsara::maintenance()->all(); ``` -------------------------------- ### Create New Samsara Instance with Custom Config (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/configuration.md Illustrates how to instantiate the Samsara SDK with custom configuration parameters, including API token, timeout, retry count, and items per page. This provides granular control over SDK behavior for specific use cases. ```php use Samsara\Samsara; $samsara = Samsara::make('api-token', [ 'timeout' => 60, 'retry' => 5, 'per_page' => 50, ]); // Use EU endpoint $samsara->useEuEndpoint(); ``` -------------------------------- ### Get IFTA Jurisdiction Report (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/ifta.md Retrieves the IFTA jurisdiction report for a specified year and quarter. Requires the Samsara SDK and authentication. ```php use Samsara\Facades\Samsara; // Get IFTA jurisdiction report $report = Samsara::ifta()->jurisdictionReport([ 'year' => 2024, 'quarter' => 1, ]); ``` -------------------------------- ### Get Trailer Assignments (Legacy) (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/assignments.md Retrieve legacy trailer assignments for a specific trailer using the Samsara PHP SDK. ```php // Get assignments for a specific trailer $assignments = Samsara::trailerAssignments() ->forTrailer('trailer-123'); ``` -------------------------------- ### Basic Driver Management with Samsara PHP SDK Source: https://github.com/erikgall/samsara/blob/main/docs/resources/drivers.md Demonstrates fundamental operations for managing drivers using the Samsara PHP SDK. This includes fetching all drivers, finding a specific driver by ID, creating a new driver, updating an existing driver's details, and deleting a driver. ```php use Samsara\Facades\Samsara; // Get all drivers $drivers = Samsara::drivers()->all(); // Find a driver $driver = Samsara::drivers()->find('driver-id'); // Create a driver $driver = Samsara::drivers()->create([ 'name' => 'John Doe', 'phone' => '+1234567890', ]); // Update a driver $driver = Samsara::drivers()->update('driver-id', [ 'phone' => '+0987654321', ]); // Delete a driver Samsara::drivers()->delete('driver-id'); ``` -------------------------------- ### Get HOS Violations (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/hours-of-service.md Retrieve Hours of Service (HOS) violations. This can be done for all drivers or filtered by specific drivers and a date range. ```php // Get all violations $violations = Samsara::hoursOfService()->violations()->get(); // Get violations for specific drivers $violations = Samsara::hoursOfService() ->violations() ->whereDriver('driver-id') ->between('2024-01-01', '2024-01-31') ->get(); ``` -------------------------------- ### Basic Query Builder Usage (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/query-builder.md Demonstrates accessing the query builder via the `query()` method on a resource or directly on resources that return a query builder. This is the starting point for constructing data retrieval requests. ```php use Samsara\Facades\Samsara; $drivers = Samsara::drivers() ->query() ->whereTag('tag-123') ->get(); ``` ```php $stats = Samsara::vehicleStats() ->types(['gps', 'engineStates']) ->get(); ``` -------------------------------- ### Get Driver-Trailer Assignments (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/assignments.md Retrieve driver-trailer assignments from Samsara. Allows filtering by a specific driver using the Samsara PHP SDK. ```php // Get driver-trailer assignments $assignments = Samsara::driverTrailerAssignments() ->query() ->get(); // Filter by driver $assignments = Samsara::driverTrailerAssignments() ->query() ->whereDriver('driver-123') ->get(); ``` -------------------------------- ### Code Formatting with Pint Source: https://github.com/erikgall/samsara/blob/main/CLAUDE.md Command to format code using the Pint tool before committing. This ensures adherence to key coding rules such as array arrow alignment, snake case for test methods, sorted imports, and removal of unused imports. ```bash vendor/bin/pint --dirty ``` -------------------------------- ### Get Driver-Vehicle Assignments (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/assignments.md Retrieve driver-vehicle assignments from Samsara. Supports filtering by specific drivers or vehicles using the Samsara PHP SDK. ```php use Samsara\Facades\Samsara; // Get driver-vehicle assignments $assignments = Samsara::driverVehicleAssignments() ->query() ->get(); // Filter by driver $assignments = Samsara::driverVehicleAssignments() ->query() ->whereDriver('driver-123') ->get(); // Filter by vehicle $assignments = Samsara::driverVehicleAssignments() ->query() ->whereVehicle('vehicle-456') ->get(); ``` -------------------------------- ### Handling AuthorizationException in PHP Source: https://github.com/erikgall/samsara/blob/main/docs/error-handling.md Demonstrates catching `AuthorizationException` in PHP, which indicates insufficient permissions for the authenticated user (HTTP 403). The example shows how to display the error message. ```php use Samsara\Facades\Samsara; use Samsara\Exceptions\AuthorizationException; try { $driver = Samsara::drivers()->delete('driver-id'); } catch (AuthorizationException $e) { echo $e->getMessage(); // "You don't have permission..." } ``` -------------------------------- ### Manage Samsara Vehicles using the SDK Source: https://context7.com/erikgall/samsara/llms.txt Illustrates how to manage vehicle resources within the Samsara platform using the SDK. This includes fetching all vehicles, finding a specific vehicle, creating, updating, and deleting vehicles, as well as finding vehicles by external ID and querying them by tags. ```php use Samsara\Facades\Samsara; // Get all vehicles $vehicles = Samsara::vehicles()->all(); // Find a specific vehicle $vehicle = Samsara::vehicles()->find('vehicle-id'); // Create a new vehicle $vehicle = Samsara::vehicles()->create([ 'name' => 'Truck 001', 'vin' => '1HGBH41JXMN109186', 'make' => 'Ford', 'model' => 'F-150', 'year' => '2024', 'licensePlate' => 'ABC1234', ]); // Update a vehicle $vehicle = Samsara::vehicles()->update('vehicle-id', [ 'name' => 'Truck 001 - Updated', ]); // Delete a vehicle Samsara::vehicles()->delete('vehicle-id'); // Find by external ID $vehicle = Samsara::vehicles()->findByExternalId('fleet_id', 'TRUCK001'); // Query vehicles by tag $vehicles = Samsara::vehicles() ->query() ->whereTag(['tag-1', 'tag-2']) ->limit(50) ->get(); // Vehicle entity helper methods $vehicle->getDisplayName(); // string $vehicle->getExternalId('fleet_id'); // ?string $vehicle->getTagIds(); // array $vehicle->hasStaticAssignedDriver(); // bool ``` -------------------------------- ### Get HOS Clocks (PHP) Source: https://github.com/erikgall/samsara/blob/main/docs/resources/hours-of-service.md Retrieve real-time Hours of Service (HOS) clock data for drivers. You can fetch clocks for all drivers or filter by specific driver IDs. ```php // Get clocks for all drivers $clocks = Samsara::hoursOfService()->clocks()->get(); // Get clocks for specific drivers $clocks = Samsara::hoursOfService() ->clocks() ->whereDriver('driver-id') ->get(); ``` -------------------------------- ### Configure Samsara API Credentials Source: https://github.com/erikgall/samsara/blob/main/README.md Sets up your Samsara API key and region in the `.env` file. These credentials are used by the SDK to authenticate with the Samsara API. ```env SAMSARA_API_KEY=your-api-token-here SAMSARA_REGION=us # or 'eu' for European API ```