Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Model Flags Laravel Package

spatie/laravel-model-flags

Add lightweight “flags” to Eloquent models via a trait—store process state without extra columns. Check, set, and clear flags, and query with flagged/notFlagged scopes. Ideal for idempotent, restartable jobs like one-time emails or migrations.

View on GitHub
Deep Wiki
Context7

Product Decisions This Supports

  • Idempotent Workflows: Enables restartable, fault-tolerant processes (e.g., batch emails, migrations, or notifications) by tracking state via flags instead of manual checks (e.g., WHERE NOT EXISTS queries).
  • Feature Flags for Internal State: Replace boolean columns (e.g., is_processed) with dynamic flags to avoid migrations and enable granular control (e.g., user->flag('beta_access')).
  • Build vs. Buy: Buy—avoids reinventing flag management (e.g., custom tables, caching layers) while supporting Laravel’s ecosystem. Justifies ~500 lines of code vs. a 10-minute integration.
  • Roadmap Priorities:
    • Scalability: Offload flag queries to avoid N+1 problems (e.g., User::notFlagged('x')->with('flags')->get()).
    • Auditability: Extend lastFlaggedAt() to track flag history (e.g., for compliance).
    • Performance: Add bulk flag operations (e.g., User::where('role', 'admin')->flag(['feature_x', 'feature_y'])).
  • Use Cases:
    • Batch Processing: Resume interrupted jobs (e.g., "Send 10K emails" without duplicates).
    • A/B Testing: Toggle features per user without schema changes.
    • Data Migration: Mark records as "processed" during ETL pipelines.

When to Consider This Package

  • Adopt if:

    • Your Laravel app needs dynamic, migration-free state tracking (e.g., flags, toggles, or process markers).
    • You’re building idempotent workflows (e.g., cron jobs, CLI scripts) where restartability is critical.
    • Your team prefers declarative syntax over raw SQL (e.g., $user->flag('verified') vs. UPDATE users SET verified_at = NOW() WHERE id = ?).
    • You’re using Laravel 11+ (fully supported) and need enum/array flag support (v1.4+).
  • Look Elsewhere if:

    • You need fine-grained permissions (use Laravel’s built-in authorizable or packages like spatie/laravel-permission).
    • Your flags require complex metadata (e.g., timestamps, user-assigned values)—consider a pivot table or JSON column.
    • You’re not using Eloquent (this is Laravel-specific).
    • Performance is critical for high-frequency flag checks (e.g., real-time systems)—cache flags in Redis or a dedicated service.
    • You need multi-tenancy isolation—this package doesn’t natively support soft-deletes or tenant-aware flags (though you could extend it).

How to Pitch It (Stakeholders)

For Executives:

"This package lets us add ‘toggle switches’ to any database record—without writing migrations or slowing down queries. For example, we can mark users as ‘eligible for a promotion’ or track which records a batch job has processed, then safely restart the job if it fails. It’s like GitHub Actions’ ‘artifacts’ but for our database: no duplicates, no missed steps, and no schema changes. The cost? Zero—it’s open-source and maintained by Spatie, who build 200M+ downloads of Laravel tools annually."

ROI:

  • Dev Velocity: Reduces boilerplate for state management (e.g., no more ALTER TABLE for new flags).
  • Reliability: Prevents duplicate work in long-running processes (e.g., "Send 50K emails" scripts).
  • Future-Proof: Supports Laravel’s latest versions and adds features like enum flags.

For Engineers:

*"This is a trait-based solution for adding key-value flags to Eloquent models, stored in a separate flags table. Think of it as a lightweight alternative to:

  • Boolean columns (is_verifiedhasFlag('verified')).
  • JSON fields (metadata → structured flags with timestamps).
  • Custom pivot tables for state tracking.

Key Benefits:

  • Zero Migrations: Add flags dynamically (e.g., user->flag('new_feature')).
  • Query Scopes: Filter models by flags (e.g., User::flagged('premium')->get()).
  • Idempotency: Perfect for batch jobs (e.g., User::notFlagged('sent_email')->each(...)).
  • Extensible: Hook into flagged() events or add custom logic via the flags() relation.

Trade-offs:

  • Adds a join to queries (mitigate with caching or bulk operations).
  • Not for high-throughput systems (e.g., real-time APIs)—better for batch/background jobs.

Example Use Case:

// In a cron job to send welcome emails:
User::notFlagged('welcome_email_sent')
    ->chunk(100, function ($users) {
        foreach ($users as $user) {
            Mail::to($user)->send(new WelcomeEmail());
            $user->flag('welcome_email_sent'); // Mark as done
        }
    });

No more: WHERE email_sent_at IS NULL + manual updates. Just flags.

Next Steps:

  1. Spike: Test with a high-traffic model (e.g., User) to measure query impact.
  2. Integrate: Add HasFlags to 2–3 critical models (e.g., Order, Subscription).
  3. Extend: Build a FlaggedEvent listener for analytics (e.g., track how often beta_access is toggled).

Alternatives Considered:

  • Boolean Columns: Fragile (requires migrations) and limited to binary states.
  • Redis: Overkill for persistence; flags need to survive app restarts.
  • Custom Pivot Table: More work than this 10-line trait.

Recommendation: Adopt for idempotent workflows and feature toggles. Pair with Laravel’s caching for high-read scenarios."*

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai