Skip to content
FlagSwiftDocs

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#

bash
composer require flagswift/flagswift-laravel
php artisan vendor:publish --tag=flagswift-config   # optional

It needs PHP 8.1 or newer. The service provider is auto-discovered, so there is nothing to register.

Placeholder package name

The Packagist name is a placeholder until the publishing location is decided, and nothing is published yet. Install from the repository for now.

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.

.env
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 store

Use a shared cache store

The configuration lives in your Laravel cache, so use a store your workers share: redis, memcached, database or file. The 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.

Common keys of config/flagswift.php
KeyTypeDescription
base_url*FLAGSWIFT_BASE_URLYour server address. No default.
api_key*FLAGSWIFT_API_KEYA server or admin key with evaluation:read. Never commit it.
environmentFLAGSWIFT_ENVIRONMENTOnly for project-wide keys.
cache_storeFLAGSWIFT_CACHE_STOREAny store from config/cache.php. Empty uses the default.
refresh_intervalFLAGSWIFT_REFRESH_INTERVALSeconds before the cached copy is revalidated. Default 30.
fallbacksAn array such as ['new-checkout' => false].
user_resolverA callable or invokable class that turns the authenticated user into an identifier or array.
middleware_statusStatus the flag: middleware aborts with. Default 404.
auto_exposuresFLAGSWIFT_AUTO_EXPOSURESQueue 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.

php
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');                             // helper

In Blade views#

The @flag directive uses the current user. @else is optional.

blade
@flag('new-checkout')
    <x-new-checkout />
@else
    <x-old-checkout />
@endflag

On 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).

php
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.

php
$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().

AppServiceProvider.php
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.

bash
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 error

Like 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.

What happens when something goes wrong
SituationDescription
A refresh failsThe 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 cachedYou get your fallbacks config, then false. The load is bounded by init_timeout (5 seconds, across retries).
Worker restarted during an outageThe cached copy is served, because it is stored with forever. Use a persistent store (redis, database, file), not array.
Cache flushed and server unreachableThere is nothing to serve, so fallbacks apply.
Missing API key or base URLA 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.

php
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 now

Without 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.

config/flagswift.php
KeyTypeDescription
base_urlFLAGSWIFT_BASE_URLYour server address. No default.
api_keyFLAGSWIFT_API_KEYA server or admin key with the evaluation:read scope. Never commit it.
environmentFLAGSWIFT_ENVIRONMENTOnly for project-wide keys.
cache_storeFLAGSWIFT_CACHE_STOREAny store from config/cache.php; empty uses the default. Use one your workers share (redis, memcached, database, file); array downloads every request.
cache_keyDefault flagswift:config.
refresh_intervalFLAGSWIFT_REFRESH_INTERVALSeconds before revalidating. Default 30.
timeout, max_retries, init_timeoutFLAGSWIFT_TIMEOUT, _MAX_RETRIES, _INIT_TIMEOUTDefaults 2 seconds, 2 retries, 5 seconds.
failure_backoffSeconds after a first failed refresh (5), doubling to five minutes.
fallbacksAn array such as ['new-checkout' => false].
report_errorsDefault true.
middleware_statusStatus the flag: middleware aborts with. Default 404.
user_resolverA callable or invokable class that receives the authenticated user and returns an identifier or an array. Default: getAuthIdentifier().
Laravel surface
PieceDescription
FlagSwift facade / FlagSwiftManagerisEnabled(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') ... @endflagBlade directive. Uses the current user.
flag:name middlewareRoute::get(...)->middleware('flag:a,b'). Every listed flag must be on, or it aborts with middleware_status.
php artisan flagswift:refreshDownload the configuration now. For deploy hooks and cache warm-up.
php artisan flagswift:statusShow the configuration the application is serving.
LaravelCacheStoreThe ConfigStore over any Laravel cache repository.