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. Installation:
    composer require spatie/laravel-float-sdk
    
  2. Configure Environment: Add to .env:
    FLOAT_API_TOKEN=your_float_api_token_here
    FLOAT_USER_AGENT="YourAppName (your-email@example.com)"
    
  3. Publish Config (optional):
    php artisan vendor:publish --tag="float-sdk-config"
    

First Use Case: Fetching a User

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

  • Service Provider: The FloatClient is auto-bound to Laravel’s container.
  • Resource Groups: Start with users(), projects(), or allocations() for common workflows.
  • Query Parameters: Use GetUsersParams, GetProjectsParams, etc., for filtering (e.g., active: true).

Implementation Patterns

Dependency Injection

Best Practice: Inject FloatClient into controllers/services.

public function __construct(protected FloatClient $float) {}
  • Why: Leverages Laravel’s IoC for testability and reusability.

Resource Workflows

1. CRUD-Like Operations

  • Fetch Single:
    $project = $this->float->projects()->get(10);
    
  • Fetch Collection:
    $users = $this->float->users()->all();
    
  • Filter Collections:
    $activeUsers = $this->float->users()->all(
        new GetUsersParams(active: true)
    );
    

2. Pagination & Sorting

$users = $this->float->users()->all(
    new GetUsersParams(
        page: 2,
        perPage: 20,
        sort: 'name'
    )
);

3. Field Selection & Relationships

$projects = $this->float->projects()->all(
    new GetProjectsParams(
        fields: ['id', 'name', 'client_id'],
        expand: ['client']
    )
);

Common Use Cases

Expense Approval Workflow

// Fetch pending allocations for approval
$allocations = $this->float->allocations()->all(
    new GetAllocationsParams(
        status: 'pending',
        startDate: now()->subDays(7)->format('Y-m-d'),
        endDate: now()->format('Y-m-d')
    )
);

// Approve via Float’s API (extend SDK if needed)
foreach ($allocations as $allocation) {
    $this->float->allocations()->approve($allocation->id);
}

Project Reporting

// Get project tasks with client details
$tasks = $this->float->projectTasks()->all(
    new GetProjectTasksParams(
        projectId: 42,
        expand: ['client']
    )
);

// Aggregate by client
$report = $tasks->groupBy('client.name');

Time Off Management

// Fetch time off types for a dropdown
$timeOffTypes = $this->float->timeOff()->types();

// Validate time off requests
$requests = $this->float->timeOff()->all(
    '2023-12-01',
    '2023-12-31',
    new GetTimeOffParams(
        status: 'pending',
        userId: auth()->id()
    )
);

Integration Tips

  1. Error Handling: Wrap SDK calls in try-catch blocks to handle API errors gracefully:

    try {
        $user = $this->float->users()->get(1);
    } catch (\Spatie\FloatSdk\Exceptions\FloatException $e) {
        Log::error("Float API Error: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    
  2. Caching: Cache frequent queries (e.g., client lists) using Laravel’s cache:

    $clients = Cache::remember('float.clients', now()->addHours(1), function () {
        return $this->float->clients()->all();
    });
    
  3. Testing: Use Laravel’s MockFloatClient (if provided) or mock the FloatClient interface:

    $this->mock(FloatClient::class, function ($mock) {
        $mock->shouldReceive('users')
             ->andReturnSelf()
             ->shouldReceive('get')
             ->with(1)
             ->andReturn(new UserVO(['id' => 1, 'name' => 'Test User']));
    });
    
  4. Extending the SDK: Create a facade or decorator for custom logic:

    class FloatService
    {
        public function __construct(protected FloatClient $float) {}
    
        public function getUserAllocations($userId)
        {
            return $this->float->allocations()->all(
                new GetAllocationsParams(userId: $userId)
            );
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Single Object Response Handling:

    • Issue: The 1.0.1 release fixed a bug where single-object responses (e.g., allocations()->get($id)) might return inconsistent data structures.
    • Workaround: Always validate responses:
      $allocation = $this->float->allocations()->get(1);
      if (!is_array($allocation)) {
          $allocation = [$allocation]; // Normalize if needed
      }
      
  2. Pagination Limits:

    • Default perPage is 50. For large datasets, paginate manually:
      $page = 1;
      do {
          $users = $this->float->users()->all(
              new GetUsersParams(page: $page, perPage: 100)
          );
          $page++;
      } while (!empty($users));
      
  3. API Rate Limits:

    • Float’s API may throttle requests. Implement exponential backoff:
      use Spatie\FloatSdk\Exceptions\RateLimitExceeded;
      
      try {
          $data = $this->float->users()->all();
      } catch (RateLimitExceeded $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Field Expansion:

    • Not all endpoints support expand. Check the Float API docs for valid relationships.
  5. Time Off Date Ranges:

    • The timeOff()->all() method expects ISO-8601 formatted dates (e.g., '2023-12-01'). Invalid formats may return empty results.

Debugging Tips

  1. Enable API Logging: Configure the underlying Saloon HTTP client to log requests:

    $this->float->withOptions(['debug' => true]);
    

    Logs will appear in storage/logs/laravel.log.

  2. Inspect Raw Responses: Access the raw API response for debugging:

    $response = $this->float->users()->get(1);
    \Log::debug($response->originalResponse->body());
    
  3. Query Parameter Validation: Use dd() to inspect generated query strings:

    $params = new GetUsersParams(active: true);
    dd($params->toArray()); // Verify parameters
    

Extension Points

  1. Custom Query Parameters: Extend existing Params classes or create new ones:

    namespace App\QueryParameters;
    
    use Spatie\FloatSdk\QueryParameters\QueryParams;
    
    class GetActiveProjectsParams extends QueryParams
    {
        public function __construct(
            public ?int $clientId = null,
            public ?string $status = 'active'
        ) {}
    }
    
  2. Response Transformers: Override response handling for specific endpoints:

    $this->float->extend('users', function ($float) {
        $float->getTransformer()->setCustomTransformer('users', function ($response) {
            return collect($response)->map(function ($user) {
                return (object) array_merge($user, ['formatted_name' => ucfirst($user->name)]);
            });
        });
    });
    
  3. Webhook Integration: Use the SDK to validate incoming Float webhooks:

    public function handleWebhook(Request $request)
    {
        $payload = $request->json();
        $user = $this->float->users()->get($payload['user_id']);
        // Validate payload against Float’s data
    }
    
  4. Testing: Mock the FloatClient for unit tests:

    $this->partialMock(FloatClient::class, function ($mock) {
        $mock
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai