Laravel Model Flags Package
Published on by Paul Redmond
Laravel Model Flags is a package by Spatie to allow you to add flags to an Eloquent model:
📦 We just released a new Laravel spatie/laravel-model-flagshttps://t.co/gy6Oa8XI7R
— Freek Van der Herten 🔭 (@freekmurze) October 21, 2022
This package can help you make your code idempotent.
✍️ I’ve described our use case in this blog post: https://t.co/tk0SNNdn7D#laravel #php pic.twitter.com/PCA9MYp2TX
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":
User::notFlagged('wasSentPromotionMail') ->each(function(User $user) { Mail::to($user->email)->send(new PromotionMail()) $user->flag('wasSentPromotionMail'); });});
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$user->flag('someExperimentalFeature'); // Now the flag returns true$user->hasFlag('someExperimentalFeature'); // Get all users with the flagUser::flagged('someExperimentalFeature')->get(); // Get all users without the flagUser::notFlagged('someExperimentalFeature')->get();
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.