• Reading time ~ 2 min
  • 08.11.2022

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

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 flag
User::flagged('someExperimentalFeature')->get();
 
// Get all users without the flag
User::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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297