PHPackages                             meius/laravel-flag-forge - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. meius/laravel-flag-forge

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

meius/laravel-flag-forge
========================

Lightweight wrapper for the meius/flag-forge library, seamlessly integrating bitwise enumeration and flag management into your Laravel applications.

v1.0.1(1y ago)120MITPHPPHP &gt;=8.2CI passing

Since Mar 11Pushed 1y ago1 watchersCompare

[ Source](https://github.com/brann-meius/laravel-flag-forge)[ Packagist](https://packagist.org/packages/meius/laravel-flag-forge)[ Fund](https://www.buymeacoffee.com/bohdanmeiuv)[ RSS](/packages/meius-laravel-flag-forge/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (8)Versions (4)Used By (0)

Laravel Flag Forge Package
==========================

[](#laravel-flag-forge-package)

[![License](https://camo.githubusercontent.com/600e542a048d5a4e731cedf32b1e32f0fc762c0a7035ad0f3c4c9b3101d7be5c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6272616e6e2d6d656975732f6c61726176656c2d666c61672d666f726765)](LICENSE)[![codecov](https://camo.githubusercontent.com/5755be4c268a24ac6b43b0fb2dc64095eab2a97c441e64385e7f1a37559bee14/68747470733a2f2f636f6465636f762e696f2f67682f6272616e6e2d6d656975732f6c61726176656c2d666c61672d666f7267652f67726170682f62616467652e7376673f746f6b656e3d59354e43343355365a45)](https://codecov.io/gh/brann-meius/laravel-flag-forge)[![Codacy Badge](https://camo.githubusercontent.com/ca013beba525f51232b19163bdf74835b873c639adad79ba64cb8791ad849d98/68747470733a2f2f6170702e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f3161393665653330316236393433393639643564613462306564386539396434)](https://app.codacy.com/gh/brann-meius/laravel-flag-forge/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)[![PHP Version](https://camo.githubusercontent.com/892aee1eacbcffed3b3bae96f95a6ab8f83193518a1123f7d58dc210af44d5df/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d2533453d382e322d626c7565)](https://www.php.net/)[![Laravel Version](https://camo.githubusercontent.com/a878b4cfdefffe2fea4a17d80a8aa87a03dbce6a300e4c3225122bd103cd9fd8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d2533453d31312e302d726564)](https://laravel.com/)

> **Recommendation:** Prior to integrating this wrapper into your application, please review the documentation for the underlying library [`meius/flag-forge`](https://github.com/brann-meius/flag-forge) to fully grasp its foundational concepts and operations.

Laravel Flag Forge is a refined and sophisticated extension that effortlessly bridges the gap between the powerful bitwise flag management capabilities of the core library and the expressive nature of Laravel applications. This package enhances your project with:

- Seamless Eloquent attribute casting,
- A fluent API for bitwise operations,
- Additional expressive query methods,
- An Artisan command to generate bitwise enum classes,
- And a convenient facade for rapid access to flag operations.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Getting Started](#getting-started)
- [Installation](#installation)
- [Usage](#usage)
    - [1. Creating Bitwise Enums](#1-creating-bitwise-enums)
    - [2. Working with Eloquent (Attribute Casting)](#2-working-with-eloquent-attribute-casting)
    - [3. Mastering Bitwise Operations](#3-mastering-bitwise-operations)
    - [4. Using the Facade](#4-using-the-facade)
    - [5. Leveraging Database Query Methods](#5-leveraging-database-query-methods)
    - [6. Integrating with Authorization Policies](#6-integrating-with-authorization-policies)
- [Support](#support)
- [License](#license)

---

Features
--------

[](#features)

- **Expressive Bitwise Operations:**
    Enjoy a comprehensive suite of methods such as `add`, `remove`, `combine`, and `toggle` for managing flags in a clear and fluent manner.
- **Elegant Flag Verification:**
    Utilize the `has` and `doesntHave` methods to effortlessly determine whether a specific flag is active.
- **Database Integration:**
    Store flags in numeric fields and retrieve them with automatic conversion to a fully featured `FlagManager`instance.
- **Eloquent Attribute Casting:**
    With the `AsMask` cast, numeric bitmask values in your models are instantly transformed into elegant `FlagManager` objects.
- **Enhanced Query Methods:**
    Filter records using expressive methods such as `whereHasFlag`, `whereDoesntHaveFlag`, `whereAllFlagsSet`, and `whereAnyFlagSet` for sophisticated query building.
- **Artisan Command:**
    Generate new bitwise enum classes effortlessly with `php artisan make:bit-enum`.
- **Convenient Facade:**
    Access and chain flag operations using the provided `Flag` facade for rapid prototyping and production-ready code.

---

Requirements
------------

[](#requirements)

- **PHP:** &gt;= 8.2
- **Laravel:** &gt;= 11.0

---

Getting Started
---------------

[](#getting-started)

To get started with the `meius/laravel-flag-forge` package, follow the installation instructions below and check out the usage examples.

---

Installation
------------

[](#installation)

1. **Composer Installation:**
    Install the package using Composer:

    ```
    composer require meius/laravel-flag-forge
    ```
2. **Register the Service Provider:**
    Manually register the service provider by adding it to your `bootstrap/providers.php` file:

    ```
    return [
        // Other service providers...
        Meius\LaravelFlagForge\Providers\FlagForgeServiceProvider::class,
    ];
    ```

---

Usage
-----

[](#usage)

### 1. Creating Bitwise Enums

[](#1-creating-bitwise-enums)

Generate a new bitwise enum class using Laravel's Artisan command. For instance, to create an enum for user permissions:

```
  php artisan make:bit-enum {name}
```

This command scaffolds a template class where you can define a series of bitwise flags such as `SendMessages`, `DeleteMessages`, `AddUsers`, etc. Customize this file to reflect the specific needs of your application.

---

### 2. Working with Eloquent (Attribute Casting)

[](#2-working-with-eloquent-attribute-casting)

Harness the power of Laravel's Eloquent by converting numeric bitmask fields into expressive `FlagManager`instances. Consider the following pivot model example:

```
namespace App\Models;

use App\Enums\Permission; // Your bitwise enum must implement Bitwiseable
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Meius\LaravelFlagForge\Casts\AsMask;

/**
 * ChatUser Model
 *
 * This eloquent model demonstrates seamless integration of bitwise flag management.
 * The `permissions` attribute is automatically cast to a `FlagManager` instance,
 * allowing for sophisticated flag operations within your domain logic.
 *
 * @property string $id
 * @property string $chat_id
 * @property string $user_id
 * @property int $permissions
 */
class ChatUser extends Pivot
{
    use HasUuids;

    protected $fillable = ['permissions'];

    protected function casts(): array
    {
        return [
            // `AsMask` converts numeric bitmask values into a `FlagManager` instance.
            // Append the fully qualified bitwise enum class after the colon.
            'permissions' => AsMask::class . ':' . Permission::class,
        ];
    }
}
```

**Example of Eloquent Operations:**

```
// Retrieve a ChatUser instance
$chatUser = ChatUser::query()->first();

// Verify if the user has the permission to send messages
if ($chatUser->permissions->has(Permission::SendMessages)) {
    echo "User is allowed to send messages.";
}

// Add the DeleteMessages flag to the user's permissions
$chatUser->permissions->add(Permission::DeleteMessages);

// Remove a flag if necessary
$chatUser->permissions->remove(Permission::SendMessages);
```

---

### 3. Mastering Bitwise Operations

[](#3-mastering-bitwise-operations)

The `FlagManager` object provides a robust API to manage bitwise flags with ease. Below are detailed examples of key methods:

- **Adding Flags:**
    Append new flags to your configuration:

    ```
    $flags = Flag::add(Permission::SendMessages);
    $flags->add(Permission::AddUsers);
    ```
- **Removing Flags:**
    Exclude specific flags:

    ```
    $flags->remove(Permission::DeleteMessages);
    ```
- **Combining Flags:**
    Merge multiple flags simultaneously:

    ```
    $flags = Flag::add(Permission::SendMessages)
        ->combine(Permission::DeleteMessages, Permission::AddUsers);
    ```
- **Toggling Flags:**
    Switch a flag’s state between active and inactive:

    ```
    $flags->toggle(Permission::PinMessages);
    ```
- **Flag Verification:**
    Check if a flag is set or unset:

    ```
    if ($flags->has(Permission::SendMessages)) {
        // Execute logic when the flag is active
    }
    if ($flags->doesntHave(Permission::RemoveUsers)) {
        // Execute alternative logic when the flag is not active
    }
    ```

Each of these operations is designed to be chainable, promoting a fluent and natural coding style that enhances readability and maintainability.

---

### 4. Using the Facade

[](#4-using-the-facade)

The `Flag` facade grants immediate access to flag management operations. It supports chaining methods for building complex configurations:

```
use App\Enums\Permission;
use Meius\LaravelFlagForge\Facades\Flag;

// Create a comprehensive flag manager instance with multiple permissions
$flagManager = Flag::add(Permission::SendMessages)
    ->combine(Permission::DeleteMessages, Permission::AddUsers)
    ->toggle(Permission::PinMessages);

// Alternatively, initialize a flag manager with a single permission for a quick check
$singleFlag = Flag::add(Permission::DeleteMessages);
```

This elegant facade simplifies the process of flag manipulation, allowing you to write succinct, expressive code.

---

### 5. Leveraging Database Query Methods

[](#5-leveraging-database-query-methods)

Laravel Flag Forge enriches your querying capabilities by providing additional methods that allow filtering based on bitwise flags.

- **Filtering Records with Specific Flags:**

    ```
    use App\Enums\Permission;
    use App\Models\ChatUser;

    // Retrieve all users who have the SendMessages permission set
    $users = ChatUser::query()
      ->whereHasFlag('permissions', Permission::SendMessages)
      ->get();
    ```
- **Excluding Records Missing Certain Flags:**

    ```
    // Retrieve users who do not have the RemoveUsers flag
    $users = ChatUser::query()
        ->whereDoesntHaveFlag('permissions', Permission::RemoveUsers)
        ->get();
    ```
- **Combining Conditions with Expressive Methods:**

    ```
    use Meius\LaravelFlagForge\Facades\Flag;

    // Retrieve users who have either the combination of SendMessages and AddUsers or the composite flag built dynamically
    $users = ChatUser::query()
      ->whereAllFlagsSet('permissions', [Permission::SendMessages, Permission::AddUsers])
      ->orWhereAllFlagsSet('permissions', Flag::add(Permission::DeleteMessages)
      ->combine(Permission::PinMessages))
      ->get();
    ```
- **Retrieving Records with Any of Multiple Flags Set:**

    ```
    // Retrieve users who have at least one flag among RemoveUsers or PinMessages set
    $users = ChatUser::query()
      ->whereAnyFlagSet('permissions', Flag::add(Permission::RemoveUsers)->add(Permission::PinMessages))
      ->get();
    ```

These query methods empower you to create finely tuned database queries, ensuring that your application logic remains both robust and highly expressive.

---

### 6. Integrating with Authorization Policies

[](#6-integrating-with-authorization-policies)

Seamlessly integrate bitwise flag management into Laravel’s authorization system. For example, consider a policy governing chat interactions. You can employ flag checks directly within policy methods to enforce nuanced permissions:

```
namespace App\Policies;

use App\Models\User;
use App\Models\Chat;
use App\Enums\Permission;

class ChatPolicy
{
    /**
     * Determine whether the user can send messages.
     */
    public function send(User $user, Chat $chat): bool
    {
        return $user->chats()
            ->where('id', '=', $chat->id)
            ->whereHasFlag('permissions', Permission::SendMessages)
            ->exists();
    }

    /**
     * Determine whether the user can moderate the chat.
     */
    public function update(User $user, Chat $chat): bool
    {
        return $user->chats()
            ->where('id', '=', $chat->id)
            ->whereHasFlag('permissions', Permission::ManageChat)
            ->exists();
    }

    /**
    * Determine whether the auth user can exclude the user from the chat.
    */
    public function exclude(User $auth, Chat $chat, User $user): bool
    {
        return $auth->id === $user->id || $auth->chats()
            ->where('id', '=', $chat->id)
            ->whereHasFlag('permissions', Permission::RemoveUsers)
            ->exists();
    }
}
```

This integration ensures that your authorization logic remains expressive and perfectly aligned with the dynamic nature of bitwise permissions.

---

Support
-------

[](#support)

For support, please open an issue on the [GitHub repository](https://github.com/brann-meius/laravel-flag-forge/issues).

### Contributing

[](#contributing)

We welcome contributions to the `meius/laravel-flag-forge` library. To contribute, follow these steps:

1. **Fork the Repository**: Fork the repository on GitHub and clone it to your local machine.
2. **Create a Branch**: Create a new branch for your feature or bugfix.
3. **Write Tests**: Write tests to cover your changes.
4. **Run Tests**: Ensure all tests pass by running `phpunit`.
5. **Submit a Pull Request**: Submit a pull request with a clear description of your changes.

For more details, refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file.

---

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance47

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 67.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

423d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9436066baff14a6bcf412f22489e9c476f7e792aed4d36db360bcc23ac1b42af?d=identicon)[brann-meius](/maintainers/brann-meius)

---

Top Contributors

[![b-meius](https://avatars.githubusercontent.com/u/174311900?v=4)](https://github.com/b-meius "b-meius (21 commits)")[![brann-meius](https://avatars.githubusercontent.com/u/177737890?v=4)](https://github.com/brann-meius "brann-meius (10 commits)")

---

Tags

bitwisebitwise-operationsconfigurationefficiencyenumerationenumsflagslaravelperformancephpphplaravelconfigurationperformanceflagsenumerationenumsbitwiseefficiencybitwise-operations

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/meius-laravel-flag-forge/health.svg)

```
[![Health](https://phpackages.com/badges/meius-laravel-flag-forge/health.svg)](https://phpackages.com/packages/meius-laravel-flag-forge)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M683](/packages/barryvdh-laravel-ide-helper)[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[laragear/preload

Effortlessly make a Preload script for your Laravel application.

119363.5k](/packages/laragear-preload)[tehwave/laravel-achievements

Simple, elegant Achievements the Laravel way

7012.8k](/packages/tehwave-laravel-achievements)[napp/xray-laravel

AWS X-Ray for Laravel applications.

61407.3k](/packages/napp-xray-laravel)[zonneplan/laravel-module-loader

Module loader for Laravel

24118.4k](/packages/zonneplan-laravel-module-loader)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
