Code Monkey home page Code Monkey logo

laravel-model-flags's Introduction

Social Card of Laravel Model Flags

Add flags to Eloquent models

Latest Version on Packagist Total Downloads

This package offers a trait that allows you to add flags to an Eloquent model. These can be used to quickly save the state of a process, update, migration, etc... to a model, without having to add an additional column using migrations.

$user->hasFlag('receivedMail'); // returns false

$user->flag('receivedMail'); // flag the user as having received the mail

$user->hasFlag('receivedMail'); // returns true

It also provides scopes to quickly query all models with a certain flag.

User::flagged('myFlag')->get(); // returns all models with the given flag
User::notFlagged('myFlag')->get(); // returns all models without the given flag

Though there are other usages, the primary use case of this package is to easily build idempotent (aka restartable) pieces of code. For example, when writing an Artisan command that sends a mail to each user. Using flags, you can make sure that when the command is cancelled (or fails) half-way through, in the second invocation, a mail will only be sent to users that haven't received one yet.

// in an Artisan command

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

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

No matter how many times you would execute this command, users would only get the mail once.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via Composer:

composer require spatie/laravel-model-flags

Behind the scenes, the flags and the relation to a model will be stored in the flags table.

To create that flags table, you must publish and run the migrations once with:

php artisan vendor:publish --tag="model-flags-migrations"
php artisan migrate

Optionally, you can publish the config file with:

php artisan vendor:publish --tag="model-flags-config"

This is the contents of the published config file:

return [
    /*
     * The model used as the flag model.
     */
    'flag_model' => Spatie\ModelFlags\Models\Flag::class,
];

Usage

To add flaggable behaviour to a model, simply make it use the Spatie\ModelFlags\Models\Concerns\HasFlags trait

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

class YourModel extends Model
{
    use HasFlags;
}

These functions will become available.

// add a flag
$model->flag('myFlag');

// returns true if the model has a flag with the given name
$model->hasFlag('myFlag');

// remove a flag
$model->unflag('myFlag');

 // returns an array with the name of all flags on the model
$model->flagNames();

// use the `flags` relation to delete all flags on a model
$user->flags()->delete();

// use the `flags` relation to delete a particular flag on a model
$user->flags()->where('name', 'myFlag')->delete();

A flag can only exist once for a model. When flagging a model with the same flag again, the updated_at attribute of the flag will be updated.

$model->flag('myFlag');

// after a while
$model->flag('myFlag'); // update_at will be updated

You can get the date of the last time a flag was used on a model.

$model->lastFlaggedAt(); // returns the update time of the lastly updated flag
$model->lastFlaggedAt('myFlag') // returns the updated_at of the `myFlag` flag on the model
$model->lastFlaggedAt('doesNotExist') // returns null if there is no flag with the given name

You'll also get these scopes:

// query all models that have a flag with the given name
YourModel::flagged('myFlag');

// query all models that have do not have a flag with the given name
YourModel::notFlagged('myFlag');

To remove a flag from all models in one go, you can delete the flag using the Spatie\ModelFlags\Models\Flag model.

use Spatie\ModelFlags\Models\Flag;

// remove myFlag from all models
Flag::where('name', 'myFlag')->delete();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

And a special thanks to Caneco for the logo ✨

License

The MIT License (MIT). Please see License File for more information.

laravel-model-flags's People

Contributors

alexvanderbist avatar caneco avatar dependabot[bot] avatar freekmurze avatar github-actions[bot] avatar jafar-albadarneh avatar laravel-shift avatar nielsvanpach avatar raksbisht avatar xico2k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

laravel-model-flags's Issues

Suggestion for closure with autoflagging

@freekmurze Fantastic work on this package; a really elegant package to a common requirement.

Any thoughts on implementing an autoflagging closure? My thinking is you'd often flag a record after doing something (or unflag in the reverse).

Taking the example from the readme.

User::notFlagged('wasSentPromotionMail')
    ->each(function(User $user) {
        Mail::to($user->email)->send(new PromotionMail())
        $user->flag('wasSentPromotionMail');
    });
});

could be implmented as

User::notFlagged('wasSentPromotionMail', function(User $user) {
   Mail::to($user->email)->send(new PromotionMail())
});

// or even
User::notFlagged('wasSentPromotionMail', fn (User $user) => Mail::to($user->email)->send(new PromotionMail()));

Notice how the $user->flag('wasSentPromotionMail'); is not specified; the autoflag solution could handle flaging if the closure didn't throw an exception (or a boolean return if we wanted to be more explicit

Obviously, the reverse could be true and a flagged query would then unflag the record after closure complete?

Thoughts? I'm happy to throw a PR up if you think it's worth it.

Suggestion for adding Properties field for context

The new package is great. Would you consider adding a properties field for additional context. This is a feature that is in your Activity Log package and proves to be quite useful. This would extend the use cases for this great new package.

Add to migration

$table->json('properties')->nullable();

Method to add data

$user->flag('receivedMail')->withProperties(['customProperty' => 'customValue']);

[question] Retrieving flag status for all records

First of all sorry for opening an issue, but Discussions is not enabled 😅

Let's pretend we have defined a receivedMail flag for our User model (not the best real world example, I know).

User::find(1)->flag('receivedMail'); // true
User::find(2)->flag('receivedMail'); // true
User::find(3)->flag('receivedMail'); // false

...and so on.

How can I retrieve (for example) all Users along with their flag status, without running n+1 queries?
Example use case: an administration panel that lists users and shows their receivedMail status.

Thank you

Use SoftDeletes on Flags model

I'd like to suggest using SoftDeletes on the Flags model.

This means that when flags are deleted you still have the original record of when the flag was added.

For example, you can mark a model (eg: a User) as “receivedMail”, however without soft deletes, if you decide to remove this flag, you wouldn't know when it was added or removed.

Using soft deletes would act as a log of not only when a flag was applied, but when it was deleted, providing an event history of the flags, making debugging flags related issues much easier as you could see the events over time.

Cannot install, got composer error

hello, im cant install your package on laravel i was also got message about:

  Problem 1
    - Root composer.json requires spatie/laravel-model-flags ^1.1 -> satisfiable by spatie/laravel-model-flags[1.1.0].
    - spatie/laravel-model-flags 1.1.0 requires spatie/laravel-package-tools ^1.13.6 -> found spatie/laravel-package-tools[1.13.6] but the package is fixed to 1.12.1 (lock file version) by a partial update and that version does not
match. Make sure you list it as an argument for the update command.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require spatie/laravel-model-flags:*" to figure out if any version is installable, or "composer require spatie/laravel-model-flags:^2.1
" if you know which you need.

Is after deletion spatie/laravel-activitylog

Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires spatie/laravel-model-flags ^1.1 -> satisfiable by spatie/laravel-model-flags[1.1.0].
    - spatie/laravel-model-flags 1.1.0 requires illuminate/contracts ^9.0 -> found illuminate/contracts[v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.

You can also try re-running composer require with an explicit version constraint, e.g. "composer require spatie/laravel-model-flags:*" to figure out if any version is installable, or "composer require spatie/laravel-model-flags:^2.1
" if you know which you need.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.