PHP code example of spatie / laravel-model-flags

1. Go to this page and download the library: Download spatie/laravel-model-flags library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

spatie / laravel-model-flags example snippets


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

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

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

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

// in an Artisan command

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

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

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

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

class YourModel extends Model
{
    use HasFlags;
}

// 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();

$model->flag('myFlag');

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

$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

// 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');

use Spatie\ModelFlags\Models\Flag;

// remove myFlag from all models
Flag::where('name', 'myFlag')->delete();
bash
php artisan vendor:publish --tag="model-flags-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="model-flags-config"