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.
Install the package:
composer require workos/workos-php-laravel
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.
Configure .env:
WORKOS_API_KEY=your_api_key_here
WORKOS_CLIENT_ID=your_project_id_here
use WorkOS\Laravel\Facades\WorkOS;
// Fetch a user by ID
$user = WorkOS::userManagement()->getUser('user-id-here');
WorkOS::userManagement()->...workos()->userManagement()->...\WorkOS\WorkOSThe package exposes WorkOS's core services through a fluent interface. Common workflows:
// 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]);
// Generate an SSO URL
$ssoUrl = WorkOS::sso()->generateSsoUrl('user-id-here', '/dashboard');
// Verify an SSO token
$token = WorkOS::sso()->verifyToken($tokenString);
// Sync a directory
$sync = WorkOS::directorySync()->syncDirectory([
'directoryId' => 'dir-id-here',
'syncMode' => 'full',
]);
// Create an admin portal session
$session = WorkOS::adminPortal()->createSession([
'userId' => 'user-id-here',
'returnTo' => url('/admin-dashboard'),
]);
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');
}
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());
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);
}
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
}
mfa() → multiFactorAuth()portal() → adminPortal()rbac() → authorization()webhook() → Split into webhooks() and webhookVerification().V6_MIGRATION_GUIDE.md before upgrading.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'),
composer require workos/workos-php-laravel:7.0.0-beta.1
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();
}
}
'debug' => env('WORKOS_DEBUG', false),
workos:debug Artisan command to inspect the client configuration:
php artisan workos:debug
$workos = app(WorkOS::class);
$workos = app()->makeWith(WorkOS::class, function ($workos) {
$workos->extend(function ($workos) {
$workos->setCustomHeader('X-Custom-Header', 'value');
});
});
public function handleWebhook($event)
{
// Process $event (e.g., user.created, sso.token.verified)
}
$user = Cache::remember("workos_user_{$userId}", now()->addHours(1), function () use ($userId) {
return WorkOS::userManagement()->getUser($userId);
});
listUsers with pagination) to minimize API calls.WORKOS_CLIENT_ID: The client_id (project ID) is required for SSO and other features. Ensure it’s set in .env.How can I help you explore Laravel packages today?