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 Cte Laravel Package

staudenmeir/laravel-cte

Adds Common Table Expression (CTE) support to Laravel’s query builder and Eloquent. Build WITH and recursive CTE queries (plus materialized, custom columns, cycle detection) across MySQL, Postgres, SQLite, SQL Server, MariaDB, Oracle, and SingleStore.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • CTE Support for Complex Queries: The package extends Laravel’s query builder and Eloquent to support Common Table Expressions (CTEs), enabling recursive queries, hierarchical data traversal, and multi-step aggregations without procedural logic. This aligns with Laravel’s declarative query philosophy and reduces application-layer complexity.

    • Hierarchical Data: Ideal for adjacency lists, nested sets, or closure tables (e.g., organizational charts, category trees).
    • Analytics/Reporting: Simplifies multi-step aggregations (e.g., rolling calculations, path-based metrics) by replacing nested subqueries or temporary tables.
    • Database Portability: Works across 10+ databases (PostgreSQL, MySQL 8.0+, SQLite, SQL Server, Oracle, SingleStore), enabling consistent query patterns across environments.
  • Performance Gains:

    • Recursive CTEs eliminate application-layer recursion (e.g., fetching all descendants of a node), reducing query count and improving scalability for deep structures (e.g., 50–200% faster for 10+ level hierarchies).
    • Materialized CTEs (PostgreSQL/SQLite) optimize read-heavy workloads by caching intermediate results.
    • Cycle Detection (PostgreSQL 14+/MariaDB 10.5.2+) prevents infinite loops in recursive queries, improving robustness.
  • Integration with Laravel Ecosystem:

    • Query Builder: Seamlessly integrates with DB::table() and DB::query().
    • Eloquent: Supports CTEs in Eloquent queries (with a trait for Laravel 5.5–5.7).
    • Lumen/Oracle: Provides manual builder instantiation for non-standard setups.
    • Composer Dependency: Lightweight (~1MB) with MIT license, minimal runtime overhead.

Integration Feasibility

  • Minimal Code Changes:

    • Installation: Single composer require command.
    • Usage: Drop-in replacement for complex queries (e.g., replace a while loop for hierarchical data with withRecursiveExpression).
    • Backward Compatibility: No breaking changes to existing queries; CTEs are optional.
  • Database Compatibility:

    • Supported: MySQL 8.0+, PostgreSQL 9.4+, SQLite 3.8.3+, SQL Server 2008+, Oracle 9.2+, SingleStore 8.1+.
    • Limitations:
      • MySQL < 8.0: No CTE support (requires upgrade or alternative approaches).
      • MariaDB < 10.5.2: No native cycle detection (workarounds possible).
      • Firebird: Dropped in v1.13.0 (if using, pin to v1.12.x).
  • Testing and Validation:

    • CI/CD Ready: Includes GitHub Actions for CI, CodeCov for coverage, and PHPStan (level 10).
    • Documentation: Comprehensive README with examples for SELECT, INSERT/UPDATE/DELETE, and recursive queries.
    • Edge Cases: Handles custom columns, materialized/non-materialized CTEs, and cycle detection.

Technical Risk

Risk Area Assessment Mitigation
Database Compatibility Some databases lack full CTE support (e.g., MySQL < 8.0). Audit target databases; upgrade or use alternatives (e.g., temporary tables).
Performance Overhead Recursive CTEs may impact performance on shallow hierarchies (<5 levels). Benchmark against procedural alternatives; use only for deep/nested data.
Cycle Detection Limited to PostgreSQL 14+/MariaDB 10.5.2. Implement application-layer checks for other databases.
Learning Curve CTE syntax differs from traditional SQL queries. Provide team training; document use cases (e.g., "Use CTEs for X, not Y").
Lumen/Oracle Support Requires manual builder instantiation. Document setup steps; consider wrapper utilities for common use cases.
Future Laravel Versions Package updates lag behind Laravel (e.g., v1.13 for Laravel 13). Monitor releases; plan for minor version upgrades.

Key Questions for Stakeholders

  1. Database Strategy:

    • Are all target databases compatible (e.g., MySQL 8.0+)? If not, what’s the upgrade/migration plan?
    • Will the application use materialized CTEs (PostgreSQL/SQLite) for read-heavy workloads?
  2. Use Cases:

    • What hierarchical or recursive data models exist (e.g., org charts, comments, categories)?
    • Are there complex analytical queries that could benefit from CTEs (e.g., multi-step aggregations)?
  3. Performance:

    • Have you benchmarked CTEs against current solutions (e.g., procedural recursion, temporary tables)?
    • What’s the expected depth/complexity of recursive queries?
  4. Team Readiness:

    • Is the team familiar with CTEs, or will training be required?
    • Are there existing SQL queries that could be refactored to use CTEs?
  5. Long-Term Maintenance:

    • How will the package be updated as Laravel evolves (e.g., PHP 9+, Laravel 14+)?
    • Are there plans to extend this for GraphQL queries or real-time updates (e.g., Laravel Echo)?

Integration Approach

Stack Fit

  • Laravel Versions: Supports Laravel 5.5–13.x (v1.0–1.13). Ensure alignment with your Laravel version:

    • Laravel 13.x → staudenmeir/laravel-cte:^1.13
    • Laravel 12.x → staudenmeir/laravel-cte:^1.12
    • Laravel 11.x → staudenmeir/laravel-cte:^1.11
  • PHP Versions: Officially supports PHP 8.3–8.4 (default); PHP 8.0+ recommended.

  • Database Stack:

    • Primary: PostgreSQL, MySQL 8.0+, SQLite 3.8.3+ (best support).
    • Secondary: SQL Server, Oracle, SingleStore (test thoroughly).
    • Legacy: Avoid MySQL < 8.0 or MariaDB < 10.2.
  • Architecture Patterns:

    • Hierarchical Data: Replace adjacency lists or nested sets with recursive CTEs.
    • Event Sourcing/CQRS: Use CTEs in read models for complex event projections.
    • Microservices: Standardize CTE usage across services for consistency.

Migration Path

  1. Assessment Phase:

    • Audit existing queries for recursive logic, nested subqueries, or temporary tables.
    • Identify high-impact candidates (e.g., slow hierarchical queries, analytical reports).
  2. Pilot Implementation:

    • Start with non-recursive CTEs (e.g., simplifying analytical queries).
    • Example:
      // Before: Nested subqueries
      $results = DB::table('orders')
          ->whereIn('customer_id', function ($query) {
              $query->select('id')->from('customers')->where('status', 'active');
          })
          ->get();
      
      // After: CTE
      $results = DB::table('orders')
          ->withExpression('active_customers', DB::table('customers')->where('status', 'active'))
          ->whereIn('customer_id', DB::table('active_customers')->select('id'))
          ->get();
      
    • Test performance gains (e.g., EXPLAIN ANALYZE in PostgreSQL).
  3. Recursive CTE Rollout:

    • Replace application-layer recursion (e.g., fetching all descendants) with withRecursiveExpression.
    • Example:
      // Before: Eloquent recursion
      $category = Category::find(1);
      $descendants = $category->descendants()->get();
      
      // After: Recursive CTE
      $tree = DB::table('categories')
          ->withRecursiveExpression('tree', function ($query) {
              $query->from('categories')
                  ->whereNull('parent_id')
                  ->unionAll(
                      DB::table('categories')
                          ->select('categories.*')
                          ->join('tree', 'tree.id', '=', 'categories.parent_id')
                  );
          })
          ->get();
      
    • Validate cycle detection for deep hierarchies (PostgreSQL 14+/MariaDB 10.5.2).
  4. Full Adoption:

    • Update Eloquent models to use CTEs where applicable (e.g., QueriesExpressions trait for Laravel < 5.8).
    • Document CTE patterns in the codebase
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