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

Conditionable Laravel Package

hyperf/conditionable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require hyperf/conditionable
    

    Register the service provider in config/autoload.php (Hyperf):

    'providers' => [
        Hyperf\Conditionable\ConditionableServiceProvider::class,
    ],
    
  2. Basic Usage Define a conditionable class (e.g., app/Models/ConditionableUser.php):

    use Hyperf\Conditionable\Conditionable;
    
    class ConditionableUser extends Conditionable
    {
        protected $conditions = [
            'is_active' => fn ($user) => $user->active,
            'is_admin'  => fn ($user) => $user->role === 'admin',
        ];
    }
    
  3. First Use Case Apply conditions in a controller or service:

    $users = ConditionableUser::query()
        ->whereCondition('is_active')
        ->whereCondition('is_admin')
        ->get();
    

Implementation Patterns

Workflow: Dynamic Condition Filtering

  1. Define Conditions Extend Conditionable and declare conditions as closures or callables:

    protected $conditions = [
        'has_permission' => fn ($model) => $model->permissions->contains('edit'),
    ];
    
  2. Apply Conditions Chain conditions in queries:

    $filtered = Model::query()
        ->whereCondition('has_permission')
        ->whereCondition('is_verified', true); // Pass args if needed
    
  3. Reusable Condition Groups Group conditions for modularity:

    public function scopeActiveAdmins($query)
    {
        return $query->whereCondition('is_active')
                    ->whereCondition('is_admin');
    }
    

Integration Tips

  • Eloquent Models: Works seamlessly with Hyperf’s Eloquent ORM.
  • Custom Logic: Conditions can reference other models or services:
    'is_eligible' => fn ($user) => $user->eligibilityService()->check(),
    
  • API Responses: Use conditions to filter collections before serialization:
    return $this->filterConditions($users, ['is_active']);
    

Gotchas and Tips

Pitfalls

  1. Performance

    • Conditions are evaluated per-row in the database layer. For large datasets, optimize with select() or exists() checks first.
    • Avoid complex logic in conditions (e.g., nested loops).
  2. Closure Scope Conditions run in the model’s scope. Access other models/services via dependency injection:

    protected $conditions = [
        'has_order' => fn ($user) => $user->orders()->exists(),
    ];
    
  3. Caching Conditions are not cached by default. Cache results if conditions are expensive:

    $cached = Cache::remember("user_{$user->id}_conditions", 3600, fn () =>
        $user->whereCondition('is_active')
    );
    

Debugging

  • Log Conditions: Temporarily log condition results:
    'debug_condition' => fn ($model) => logger()->debug('Condition', ['model' => $model->toArray()]),
    
  • Query Builder: Use toSql() to inspect generated queries:
    $query = Model::whereCondition('is_active');
    logger()->info($query->toSql(), $query->getBindings());
    

Extension Points

  1. Custom Condition Types Extend Hyperf\Conditionable\Contracts\Condition for advanced logic:

    class CustomCondition implements Condition
    {
        public function evaluate($model, ...$args) { ... }
    }
    
  2. Global Conditions Register conditions globally in the service provider:

    Conditionable::extend('global_condition', fn ($model) => $model->someGlobalCheck());
    
  3. Condition Validation Validate conditions before query execution:

    if (!$this->validateCondition('is_active')) {
        throw new \RuntimeException('Invalid condition');
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity