Laravel SDK
Facade, Blade @flag directive and route middleware.
Use this package in Laravel 10 to 13 applications. It is a thin layer over the PHP SDK: flags are evaluated locally from a configuration kept in your Laravel cache, so a check costs microseconds and never a network call. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
composer require flagswift/flagswift-laravel- Requires
- Laravel 10 to 13
- Key
- Server key (fs_srv_)
- Evaluates
- Locally, in memory
- Real-time updates
- No, it polls
- Works offline from
- Your Laravel cache
- Outcome analytics
- Yes
- Verified
- Tested against stand-ins for Laravel only
Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.
Installation#
composer require flagswift/flagswift-laravel
php artisan vendor:publish --tag=flagswift-config # optionalIt needs PHP 8.1 or newer. The service provider is auto-discovered, so there is nothing to register.
Placeholder package name
Initialization#
You need a server key (fs_srv_…) or admin key with the evaluation:read scope, and the address of your FlagSwift server. Put both in .env. The key stays on the server.
FLAGSWIFT_BASE_URL=https://flags.example.com
FLAGSWIFT_API_KEY=fs_srv_...
# FLAGSWIFT_ENVIRONMENT=production # project-wide keys only
# FLAGSWIFT_CACHE_STORE=redis # default: your default cache storeUse a shared cache store
array store downloads the configuration on every request.Connection options#
Every setting lives in config/flagswift.php, and most read an environment variable. A missing key or base URL throws a clear exception the first time flags are used.
| Key | Type | Description |
|---|---|---|
| base_url* | FLAGSWIFT_BASE_URL | Your server address. No default. |
| api_key* | FLAGSWIFT_API_KEY | A server or admin key with evaluation:read. Never commit it. |
| environment | FLAGSWIFT_ENVIRONMENT | Only for project-wide keys. |
| cache_store | FLAGSWIFT_CACHE_STORE | Any store from config/cache.php. Empty uses the default. |
| refresh_interval | FLAGSWIFT_REFRESH_INTERVAL | Seconds before the cached copy is revalidated. Default 30. |
| fallbacks | An array such as ['new-checkout' => false]. | |
| user_resolver | A callable or invokable class that turns the authenticated user into an identifier or array. | |
| middleware_status | Status the flag: middleware aborts with. Default 404. | |
| auto_exposures | FLAGSWIFT_AUTO_EXPOSURES | Queue an exposure on every read. Default false. |
Check flags#
With no user argument, the facade checks the authenticated user. Pass an identifier or an array to check someone else.
use FlagSwiftLaravelFacadesFlagSwift;
FlagSwift::isEnabled('new-checkout'); // the authenticated user
FlagSwift::isEnabled('new-checkout', 'user-42'); // an explicit identifier
FlagSwift::isEnabled('new-checkout', ['identifier' => '42', 'account' => 'acme', 'attributes' => ['plan' => 'pro']]);
feature('new-checkout'); // helperIn Blade views#
The @flag directive uses the current user. @else is optional.
@flag('new-checkout')
<x-new-checkout />
@else
<x-old-checkout />
@endflagOn routes#
The flag middleware makes a route exist only when its flags are on. List several and every one must be on, or the request aborts with middleware_status (404 by default).
Route::get('/checkout', CheckoutController::class)->middleware('flag:new-checkout');
Route::get('/beta', BetaController::class)->middleware('flag:beta,beta-reports');Check variants and values#
A flag can serve a named variant, such as a button colour or a plan limit.
$variant = FlagSwift::variant('button-colour'); // 'blue', 'green' or null
$colour = FlagSwift::value('button-colour', null, 'blue'); // the variant's value, or 'blue'
$result = FlagSwift::evaluate('button-colour'); // enabled, reason, found, variant, value
$all = FlagSwift::all();Describe the person#
By default the user is the authenticated user's getAuthIdentifier(). Guests have no identifier, so percentage rollouts give them the “off” side. To send an account or attributes for targeting, tell the package how to build the user, usually in AppServiceProvider::boot().
FlagSwift::resolveUserUsing(fn ($user) => $user ? [
'identifier' => (string) $user->id,
'account' => (string) $user->team_id,
'attributes' => ['plan' => $user->plan, 'country' => $user->country],
] : null);Or set user_resolver in config/flagswift.php to an invokable class. FlagSwift::currentUser() returns what the resolver produces for the current request.
Artisan commands#
Both commands help in deploys and when you wonder what a worker is serving.
php artisan flagswift:refresh # download the configuration now, for deploy hooks and cache warm-up
php artisan flagswift:status # show the configuration the application is serving, and the last errorLike the PHP SDK, Laravel has no real-time stream: the cached copy is revalidated every refresh_interval seconds with a conditional request. Octane and queue workers are supported, since the client re-checks after each interval.
Offline and errors#
Once a configuration is in your cache, evaluation is local. It keeps working with no internet and through a FlagSwift outage, and it never throws from FlagSwift::isEnabled() and friends.
| Situation | Description |
|---|---|
| A refresh fails | The last good configuration stays in the cache. Workers back off for failure_backoff seconds (5, doubling to five minutes) instead of piling on. php artisan flagswift:status shows the last error. |
| First load, nothing cached | You get your fallbacks config, then false. The load is bounded by init_timeout (5 seconds, across retries). |
| Worker restarted during an outage | The cached copy is served, because it is stored with forever. Use a persistent store (redis, database, file), not array. |
| Cache flushed and server unreachable | There is nothing to serve, so fallbacks apply. |
| Missing API key or base URL | A clear exception the first time flags are used. |
Testing your app#
For fully offline tests, bind a fake FlagSwift\Transport in the container, or swap the facade's client with a FlagSwift\Client built with a bootstrap payload and refreshInterval: -1.
Outcome analytics#
Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or enable auto_exposures, and only the person's identifier, the flag, the variant and the event name leave your server.
FlagSwift::trackExposure('button-colour'); // the current user was shown this flag
FlagSwift::track('purchase', null, 19.99); // an outcome for the current user; the value is optional
FlagSwift::track('signup', ['identifier' => 'u-9']); // or pass a user explicitly
FlagSwift::flushAnalytics(); // send nowWithout a user these use the same resolver as evaluation, and a guest is ignored. Items are queued and sent when the application terminates. See Outcomes for how results are read in the console.
Reference#
Package flagswift/flagswift-laravel for Laravel 10 to 13, built on the PHP SDK with your Laravel cache as the store. The provider is auto-discovered.
| Key | Type | Description |
|---|---|---|
| base_url | FLAGSWIFT_BASE_URL | Your server address. No default. |
| api_key | FLAGSWIFT_API_KEY | A server or admin key with the evaluation:read scope. Never commit it. |
| environment | FLAGSWIFT_ENVIRONMENT | Only for project-wide keys. |
| cache_store | FLAGSWIFT_CACHE_STORE | Any store from config/cache.php; empty uses the default. Use one your workers share (redis, memcached, database, file); array downloads every request. |
| cache_key | Default flagswift:config. | |
| refresh_interval | FLAGSWIFT_REFRESH_INTERVAL | Seconds before revalidating. Default 30. |
| timeout, max_retries, init_timeout | FLAGSWIFT_TIMEOUT, _MAX_RETRIES, _INIT_TIMEOUT | Defaults 2 seconds, 2 retries, 5 seconds. |
| failure_backoff | Seconds after a first failed refresh (5), doubling to five minutes. | |
| fallbacks | An array such as ['new-checkout' => false]. | |
| report_errors | Default true. | |
| middleware_status | Status the flag: middleware aborts with. Default 404. | |
| user_resolver | A callable or invokable class that receives the authenticated user and returns an identifier or an array. Default: getAuthIdentifier(). |
| Piece | Description |
|---|---|
| FlagSwift facade / FlagSwiftManager | isEnabled(flag, user?, fallback?), evaluate, variant, value and all, plus client(), resolveUserUsing(callable) and currentUser(). Other calls pass through to the client. |
| trackExposure(flag, user?) / track(event, user?, value?) | Report that the current user was shown a flag, and what they then did. The config key auto_exposures turns on automatic exposures (default false). |
| feature('flag', $user?, $fallback?) | Helper: is the flag on? |
| @flag('name') ... @endflag | Blade directive. Uses the current user. |
| flag:name middleware | Route::get(...)->middleware('flag:a,b'). Every listed flag must be on, or it aborts with middleware_status. |
| php artisan flagswift:refresh | Download the configuration now. For deploy hooks and cache warm-up. |
| php artisan flagswift:status | Show the configuration the application is serving. |
| LaravelCacheStore | The ConfigStore over any Laravel cache repository. |