Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Float Sdk Laravel Package

spatie/laravel-float-sdk

Laravel-friendly SDK for interacting with the Float.com API (v3). Configure your API token and user agent via .env/config and use the provided FloatClient to access Float endpoints. Not a full API implementation; contributions welcome.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require spatie/laravel-float-sdk
    
  2. Configure environment variables in .env:
    FLOAT_API_TOKEN=your_float_api_token_here
    FLOAT_USER_AGENT="YourAppName (your-email@example.com)"
    
  3. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --tag="float-sdk-config"
    

First Use Case: Fetching a User

Inject the FloatClient into a controller or service and retrieve a user by ID:

use Spatie\FloatSdk\FloatClient;

class UserController extends Controller
{
    public function __construct(protected FloatClient $float) {}

    public function show($id)
    {
        $user = $this->float->users()->get($id);
        return response()->json($user);
    }
}

Key Starting Points

  • Resource Groups: Explore available endpoints (users(), projects(), allocations(), etc.) in the README.
  • Query Parameters: Use GetUsersParams, GetProjectsParams, etc., for filtering, pagination, and field selection.
  • Service Container: The FloatClient is auto-bound, so dependency injection works out of the box.

Implementation Patterns

Dependency Injection Workflow

  1. Inject the Client:
    public function __construct(protected FloatClient $float) {}
    
  2. Chain Resource Methods:
    $this->float->projects()->all(new GetProjectsParams(clientId: 10));
    
  3. Handle Responses:
    • Single objects (e.g., get(1)) return a Value Object (VO).
    • Collections (e.g., all()) return a Collection of VOs.

Common Patterns by Use Case

1. Expense Approval Workflow

  • Fetch pending allocations:
    $allocations = $this->float->allocations()->all(
        new GetAllocationsParams(
            status: 'pending',
            startDate: now()->subDays(7)->format('Y-m-d'),
            endDate: now()->format('Y-m-d')
        )
    );
    
  • Update allocation status (if supported in future versions):
    $this->float->allocations()->update($id, ['status' => 'approved']);
    

2. Project Budget Tracking

  • Fetch project with client details:
    $project = $this->float->projects()->get(10, new GetProjectsParams(
        expand: ['client']
    ));
    
  • Calculate spent vs. budget:
    $allocations = $this->float->allocations()->all(
        new GetAllocationsParams(projectId: $project->id)
    );
    $totalSpent = $allocations->sum(fn ($a) => $a->amount);
    

3. Time Off Management

  • Fetch time off for a date range:
    $timeOffs = $this->float->timeOff()->all(
        now()->startOfYear()->format('Y-m-d'),
        now()->endOfYear()->format('Y-m-d')
    );
    
  • Sync with internal HR system:
    foreach ($timeOffs as $to) {
        // Map to your HR model
        YourHrModel::updateOrCreate(
            ['employee_id' => $to->userId],
            ['time_off_type' => $to->type, 'dates' => $to->dates]
        );
    }
    

4. Client Reporting

  • Generate client overview:
    $client = $this->float->clients()->get(5, new GetClientsParams(
        expand: ['projects']
    ));
    $projects = $client->projects;
    $projectStats = $projects->map(fn ($p) => [
        'name' => $p->name,
        'budget' => $p->budget,
        'spent' => $this->calculateSpentForProject($p->id),
    ]);
    

Integration Tips

  • Laravel Events: Trigger events on Float API responses (e.g., float.allocation.created).
  • Queues: Offload heavy Float API calls to queues:
    SyncFloatData::dispatch($floatClient)->onQueue('float-sync');
    
  • Caching: Cache frequent queries (e.g., user lists) with Laravel’s cache:
    $users = Cache::remember('float.users.all', now()->addHours(1), fn () =>
        $this->float->users()->all()
    );
    
  • Error Handling: Wrap API calls in try-catch:
    try {
        $data = $this->float->projects()->get($id);
    } catch (FloatApiException $e) {
        Log::error("Float API error: {$e->getMessage()}");
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    

Gotchas and Tips

Pitfalls

  1. Single Object Response Handling:

    • Issue: The get() method may return a single object or an array depending on the API response. As seen in PR #28, this can cause parsing errors.
    • Fix: Always treat get() responses as Value Objects (VOs) and avoid assuming array structure:
      $allocation = $this->float->allocations()->get(1);
      // Use $allocation->property instead of $allocation['property']
      
  2. Pagination Limits:

    • The default perPage is 50. For large datasets, implement manual pagination:
      $page = 1;
      do {
          $users = $this->float->users()->all(
              new GetUsersParams(page: $page, perPage: 100)
          );
          // Process $users
          $page++;
      } while ($users->count() > 0);
      
  3. Field Selection:

    • Gotcha: Not all fields are available for selection via fields parameter. Refer to the Float API docs for supported fields.
    • Tip: Use expand to include related data (e.g., expand: ['client'] for projects).
  4. Rate Limiting:

    • Float’s API may throttle requests. Implement exponential backoff:
      use Spatie\FloatSdk\Exceptions\FloatApiException;
      
      try {
          $data = $this->float->users()->all();
      } catch (FloatApiException $e) {
          if ($e->getCode() === 429) {
              sleep(2); // Retry after 2 seconds
              retry();
          }
      }
      
  5. Time Zone Handling:

    • Float uses UTC for dates. Convert to user’s timezone:
      $allocations = $this->float->allocations()->all(
          new GetAllocationsParams(
              startDate: now('America/New_York')->startOfMonth()->format('Y-m-d'),
              endDate: now('America/New_York')->endOfMonth()->format('Y-m-d')
          )
      );
      

Debugging Tips

  • Enable Debugging: Set the debug config option to true to log API requests:
    'debug' => env('FLOAT_DEBUG', false),
    
  • Inspect Raw Responses: Access the underlying Saloon HTTP client for debugging:
    $response = $this->float->users()->get(1)->getResponse();
    Log::debug($response->body());
    
  • Validate API Token: Ensure FLOAT_API_TOKEN is correct. Test with a simple call:
    $this->float->users()->all()->isEmpty(); // Should return false if token is valid
    

Extension Points

  1. Custom Query Parameters:

    • Extend existing Params classes or create new ones for unsupported filters:
      namespace App\Float;
      
      use Spatie\FloatSdk\QueryParameters\QueryParams;
      
      class GetUsersByRoleParams extends QueryParams
      {
          public function __construct(
              public ?string $role = null,
              public ?int $page = 1,
              public ?int $perPage = 50
          ) {}
      }
      
    • Register the custom param in the FloatClient service provider.
  2. Add Missing Endpoints:

    • Contribute new resource groups by extending FloatClient:
      namespace App\Extensions\Float;
      
      use Spatie\FloatSdk\FloatClient as BaseFloatClient;
      
      class ExtendedFloatClient extends BaseFloatClient
      {
          public function customEndpoint()
          {
              return $this->saloon->send(new CustomEndpointRequest());
          }
      }
      
    • Bind the extended client in config/app.php:
      'bindings
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi