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

Expression Language Laravel Package

symfony/expression-language

Symfony ExpressionLanguage provides an engine to compile and evaluate one-line expressions that return values (often booleans). Use it to embed simple, safe business rules and conditions in your app, with support for custom functions and variables.

View on GitHub
Deep Wiki
Context7

Product Decisions This Supports

  • Dynamic Business Logic: Enable non-technical teams (e.g., product, marketing) to configure rules via admin panels (e.g., Laravel Nova, Filament) without code deployments. Examples:

    • Feature Flags: Toggle features per user segment with expressions like 'user.subscription.tier >= 2 && user.country === "EU" && date.between("2024-01-01", "2024-12-31")'.
    • Dynamic Pricing: Adjust discounts or promotions based on user attributes (e.g., 'order.total > 100 && user.isFirstTimeBuyer()').
    • Workflow Automation: Define approval paths in a workflow_rules table (e.g., 'status === "reviewed" && (manager_approved || team_lead_approved)').
  • Build vs. Buy Decision:

    • Buy: Avoid reinventing a secure expression parser. This package is battle-tested (2,800+ stars, 8+ years of maintenance), MIT-licensed, and integrates natively with Laravel/Symfony.
    • Custom Alternative: Only justify building a custom solution if requirements are highly specialized (e.g., domain-specific syntax) or performance-critical (e.g., 100K+ evaluations/sec with unique optimizations).
    • Open-Source Contribution: Leverage Symfony’s active development (e.g., recent PHP 8.4 support, null safety fixes) instead of maintaining a fork.
  • Roadmap Priorities:

    • Configuration-Driven Features: Prioritize features where rules evolve frequently (e.g., compliance updates, A/B tests, seasonal promotions).
    • Security-Critical Logic: Use for systems where injection risks are unacceptable (e.g., payment processing, admin dashboards). Compiled expressions mitigate eval() risks.
    • Performance Optimization: Cache compiled expressions for high-frequency use cases (e.g., API rate limiting, policy checks in loops).
    • Laravel Ecosystem Expansion: Integrate with existing components like Policies, Middleware, Form Requests, and Nova to reduce boilerplate.
  • Laravel-Specific Use Cases:

    • Policies: Replace verbose if chains in App\Policies\UserPolicy with expressions stored in a database.
    • Middleware: Dynamically route or authorize requests (e.g., 'user.hasPermission("access_dashboard") && request.path !== "/admin/backup"').
    • Form/Request Validation: Validate submissions with rules stored in a validation_rules table (e.g., 'document_type in ["passport", "driver_license"] && document.expiresAfter(date.today())').
    • Feature Flags: Implement granular toggles (e.g., 'feature_enabled && user.isBetaTester() && user.region === "NA"') via a feature_flags table.
    • Workflow Automation: Define multi-step processes with conditions (e.g., 'order.status === "pending" && payment.processed()').

When to Consider This Package

Adopt When:

  • Dynamic Rules Are Critical: Logic must change frequently without code deployments (e.g., marketing campaigns, compliance updates, or A/B tests).
  • Performance Requirements Exist: Expressions are evaluated repeatedly (e.g., in loops, high-traffic APIs, or real-time systems). Compilation to PHP ensures low-latency evaluations.
  • Security Is a Priority: Need to avoid eval() risks while supporting dynamic logic. The package compiles expressions to PHP and supports variable whitelisting.
  • Laravel/Symfony Ecosystem Is Used: Already using Symfony components or planning to adopt more. Seamless integration with Laravel’s service container and PSR standards.
  • Use Cases Align:
    • Dynamic Access Control: Role-based or attribute-based access decisions (e.g., 'Allow if user.department === "finance" && request.path.startsWith("/payments")').
    • Validation Rules: Store validation logic in a database (e.g., 'Require document_type === "passport" || document_type === "driver_license" && document.expiresAfter(date.today())').
    • Feature Flags: Toggle features per user with complex conditions (e.g., 'Enable for user.subscription.tier >= 2 && user.country === "US" && date.isWeekday()').
    • Workflow Conditions: Define approval paths dynamically (e.g., 'Route to manager if order.amount > 1000 && user.isNewCustomer()').

Look Elsewhere When:

  • Rules Are Static: Logic is simple and unlikely to change (e.g., if ($user->isAdmin())). Use native PHP if/else or Laravel’s built-in helpers (e.g., Gate::forUser()).
  • Untrusted Input Is Evaluated: Raw user-provided expressions pose code injection risks. Use predefined rules or a sandboxed environment (e.g., a custom parser with strict input validation).
  • Complex Workflows Require State Machines: Multi-step processes with branching logic. Use a dedicated workflow engine (e.g., Laravel Nova Workflows, Camunda, or Symfony Workflow).
  • Legacy PHP Is Required: The package requires PHP 8.1+ (Symfony 7.x+) or 8.4+ (Symfony 8.x). Laravel 9/10 users may need to test compatibility or downgrade Symfony.
  • Non-Laravel/Symfony Stack Is Used: Overhead of integrating a Symfony component may not justify benefits (e.g., in a pure WordPress, custom PHP, or Node.js app).
  • Custom Syntax Is Mandatory: Domain-specific requirements (e.g., mathematical notation, industry jargon) may necessitate a custom solution.

How to Pitch It (Stakeholders)

For Executives:

*"This package eliminates bottlenecks between product teams and engineering by enabling self-service rule management. Here’s how it drives value:

Key Benefits:

  1. Faster Iterations:
    • Marketing can update promotion rules (e.g., 'Discount 20% if user.visited > 3 && cart.total > 50') via a CMS—no dev cycles.
    • Product can toggle features per user segment (e.g., 'Enable dark mode for users in EU') without deployments.
  2. Reduced Technical Debt:
    • No hardcoded if chains in policies or middleware. Rules live in configurable tables, not code.
    • Example: Replace 50 lines of UserPolicy logic with a single database row.
  3. Scalable Security:
    • No eval() risks: Expressions compile to PHP and run in a sandboxed environment with variable whitelisting.
    • Ideal for high-stakes systems (e.g., payments, admin dashboards).
  4. Cost Efficiency:
    • MIT-licensed and battle-tested (2,800+ stars, 8+ years of maintenance). No need to build or maintain a custom parser.

Use Cases to Pilot:

  • Feature Flags: Let product teams enable features for specific users (e.g., beta testers, regions).
  • Dynamic Pricing: Adjust discounts based on user behavior (e.g., 'First-time buyers get 15% off').
  • Access Control: Grant permissions via admin panels (e.g., 'Edit content if user.role === "editor" && content.status === "draft"').

Risk Mitigation:

  • Start with non-critical rules (e.g., feature flags) to validate performance and security.
  • Enforce strict input validation and audit logging for compiled expressions.
  • Partner with engineering to whitelist only trusted variables (e.g., user, request, date).

ROI: Weeks saved per year in rule updates, with zero increase in security risk."


For Engineering:

*"This is a secure, high-performance alternative to custom expression parsers or eval(). Here’s why it’s a smart choice for Laravel:

Technical Advantages:

  1. Compile to PHP:
    • Expressions are cached as optimized PHP for low-latency evaluations (critical for high-traffic policies).
    • Example: A policy checking 'user.hasPermission("edit_post") && post.publishedAt < date.today()' compiles to static PHP, not dynamic code.
  2. Laravel-Native Integration:
    • Works seamlessly with Policies, Middleware, Form Requests, and Nova.
    • Example: Replace public function update(UpdateUserRequest $request) with:
      $expression = 'user.canEditProfile() && request.hasValidSignature()';
      if (!$this->expressionLanguage->evaluate($expression, ['user' => $user, 'request' => $request])) {
          abort(403);
      }
      
  3. Security by Design:
    • No eval(): Compiled to safe PHP code.
    • Variable Whitelisting: Only allow trusted providers (e.g., user, request, date).
    • Null Safety: Supports ?. operator to avoid runtime errors.
  4. Future-Proof:
    • Al
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport