Laravel Model Flags Package | Laravel News


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:

1use Illuminate\Database\Eloquent\Model;

2use Spatie\ModelFlags\Models\Concerns\HasFlags;

3 

4class User extends Model

5{

6 use HasFlags;

7}

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”:

1User::notFlagged('wasSentPromotionMail')

2 ->each(function(User $user) {

3 Mail::to($user->email)->send(new PromotionMail())

4 

5 $user->flag('wasSentPromotionMail');

6 });

7});

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:

1$user->hasFlag('someExperimentalFeature'); // returns bool

2 

3// Flag the user for someExperimentalFeature

4$user->flag('someExperimentalFeature');

5 

6// Now the flag returns true

7$user->hasFlag('someExperimentalFeature');

8 

9// Get all users with the flag

10User::flagged('someExperimentalFeature')->get();

11 

12// Get all users without the flag

13User::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.



Source link

Share

Leave a Reply

Your email address will not be published. Required fields are marked *