Laravel Model Flags Package


October 28th, 2022

Laravel Model Flags Package

Laravel Model Flags is a package by Spatie to allow you to add flags to an Eloquent model:

This package adds a HasFlags trait to Eloquent models enabling you to query models that are either flagged or not flagged. The trait includes relations, model scopes, and other methods for working with flags:

use Illuminate\Database\Eloquent\Model;
use Spatie\ModelFlags\Models\Concerns\HasFlags;
class User extends Model
use HasFlags;

The package also supports a configurable "flag" model, if you want/need to override the default model that backs model flags.

Using the above model, an example in the readme shows that you can "easily build idempotent (aka restartable) pieces of code":

->each(function(User $user) {
Mail::to($user->email)->send(new PromotionMail())

The example code only runs for users not flagged, therefore, the code will skip them on subsequent calls. Without the above code, you'd have to find some way to track whether the code sent the user an email in the event of a failure.

This package also opens up general model flagging use-cases, such as things like rolling out a new feature to a subset of users:

$user->hasFlag('someExperimentalFeature'); // returns bool
// Flag the user for someExperimentalFeature
// Now the flag returns true
// Get all users with the flag
// Get all users without the flag

You can learn more about this package, get full installation instructions, and view the source code on GitHub. Also, read A Laravel package to add flags to Eloquent models, which has background details on why Spatie created this package and their primary use case.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.