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

Workos Php Laravel Laravel Package

workos/workos-php-laravel

Laravel integration for the WorkOS API. Provides a configured WorkOS client via service provider, facade, helper, or dependency injection to access services like User Management and SSO. Install with Composer and set WORKOS_API_KEY and WORKOS_CLIENT_ID.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require workos/workos-php-laravel
    
  2. Publish the config:

    php artisan vendor:publish --provider="WorkOS\Laravel\WorkOSServiceProvider"
    

    This generates a .env file with WORKOS_API_KEY and WORKOS_CLIENT_ID placeholders.

  3. Configure .env:

    WORKOS_API_KEY=your_api_key_here
    WORKOS_CLIENT_ID=your_project_id_here
    

First Use Case: Fetch a User

use WorkOS\Laravel\Facades\WorkOS;

// Fetch a user by ID
$user = WorkOS::userManagement()->getUser('user-id-here');

Key Entry Points

  • Facade: WorkOS::userManagement()->...
  • Helper: workos()->userManagement()->...
  • Dependency Injection: Constructor inject \WorkOS\WorkOS

Implementation Patterns

1. Service Access Patterns

The package exposes WorkOS's core services through a fluent interface. Common workflows:

User Management

// Create a user
$user = WorkOS::userManagement()->createUser([
    'email' => 'user@example.com',
    'firstName' => 'John',
    'lastName' => 'Doe',
]);

// List users with pagination
$users = WorkOS::userManagement()->listUsers(['limit' => 10]);

SSO (Single Sign-On)

// Generate an SSO URL
$ssoUrl = WorkOS::sso()->generateSsoUrl('user-id-here', '/dashboard');

// Verify an SSO token
$token = WorkOS::sso()->verifyToken($tokenString);

Directory Sync

// Sync a directory
$sync = WorkOS::directorySync()->syncDirectory([
    'directoryId' => 'dir-id-here',
    'syncMode' => 'full',
]);

Admin Portal

// Create an admin portal session
$session = WorkOS::adminPortal()->createSession([
    'userId' => 'user-id-here',
    'returnTo' => url('/admin-dashboard'),
]);

2. Dependency Injection

Inject the \WorkOS\WorkOS client directly into controllers/services:

use WorkOS\WorkOS;

public function __construct(private WorkOS $workos) {}

public function handleRequest()
{
    $user = $this->workos->userManagement()->getUser('user-id-here');
}

3. Webhook Handling

WorkOS supports webhook verification and event handling. Example:

use WorkOS\Laravel\Facades\WorkOS;

// Verify a webhook signature
$isValid = WorkOS::webhookVerification()->verifyWebhook(
    $request->header('X-Signature'),
    $request->getContent()
);

// Handle webhook events (e.g., in a route)
$event = WorkOS::webhooks()->parseWebhook($request->getContent());

4. Error Handling

Wrap API calls in try-catch blocks to handle WorkOS-specific exceptions:

use WorkOS\Exceptions\WorkOSException;

try {
    $user = WorkOS::userManagement()->getUser('invalid-id');
} catch (WorkOSException $e) {
    // Handle error (e.g., log or return a user-friendly message)
    report($e);
    return response()->json(['error' => 'User not found'], 404);
}

5. Testing

Mock the WorkOS client in tests using Laravel's mocking:

use WorkOS\WorkOS;

public function test_user_creation()
{
    $mock = Mockery::mock(WorkOS::class);
    $mock->shouldReceive('userManagement')
         ->andReturnSelf()
         ->shouldReceive('createUser')
         ->with(['email' => 'test@example.com'])
         ->andReturn(['id' => 'user-id']);

    $this->app->instance(WorkOS::class, $mock);

    // Test your logic here
}

Gotchas and Tips

1. Breaking Changes in v6+

  • Service Renames: Upstream renamed several services:
    • mfa()multiFactorAuth()
    • portal()adminPortal()
    • rbac()authorization()
    • webhook() → Split into webhooks() and webhookVerification().
  • Migration Guide: Always check V6_MIGRATION_GUIDE.md before upgrading.

2. Environment Variables

  • The package defaults to WORKOS_API_KEY and WORKOS_CLIENT_ID, but you can override these in the published config file (config/workos.php):
    'api_key' => env('WORKOS_API_KEY', 'fallback-key'),
    'client_id' => env('WORKOS_CLIENT_ID', 'fallback-project-id'),
    

3. Beta Features

  • Beta releases may introduce breaking changes. Pin the package version to avoid unexpected updates:
    composer require workos/workos-php-laravel:7.0.0-beta.1
    
  • Monitor the WorkOS changelog for Beta → GA transitions.

4. Rate Limiting

  • WorkOS enforces rate limits. Handle 429 Too Many Requests responses gracefully:
    try {
        $response = WorkOS::userManagement()->listUsers();
    } catch (WorkOSException $e) {
        if ($e->getCode() === 429) {
            // Implement retry logic with exponential backoff
            sleep(2 ** $retryAttempt);
            retry();
        }
    }
    

5. Debugging

  • Enable debug mode in the config to log API requests:
    'debug' => env('WORKOS_DEBUG', false),
    
  • Use the workos:debug Artisan command to inspect the client configuration:
    php artisan workos:debug
    

6. Extension Points

  • Custom Middleware: Extend the WorkOS client by wrapping it in middleware:
    $workos = app(WorkOS::class);
    $workos = app()->makeWith(WorkOS::class, function ($workos) {
        $workos->extend(function ($workos) {
            $workos->setCustomHeader('X-Custom-Header', 'value');
        });
    });
    
  • Event Listeners: Listen to WorkOS webhook events in Laravel:
    public function handleWebhook($event)
    {
        // Process $event (e.g., user.created, sso.token.verified)
    }
    

7. Performance Tips

  • Caching: Cache frequently accessed user data or SSO tokens:
    $user = Cache::remember("workos_user_{$userId}", now()->addHours(1), function () use ($userId) {
        return WorkOS::userManagement()->getUser($userId);
    });
    
  • Batch Operations: Use bulk endpoints (e.g., listUsers with pagination) to minimize API calls.

8. Common Pitfalls

  • Missing WORKOS_CLIENT_ID: The client_id (project ID) is required for SSO and other features. Ensure it’s set in .env.
  • Incorrect Redirect URIs: For SSO, configure allowed redirect URIs in the WorkOS dashboard to match your Laravel app’s routes.
  • Token Expiry: SSO tokens and API keys may expire. Implement refresh logic or monitor WorkOS’s API status page.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor