staudenmeir/laravel-cte
Add Common Table Expression (CTE) support to Laravel’s query builder and Eloquent, including recursive and materialized CTEs. Works across MySQL, MariaDB, PostgreSQL, SQLite, SQL Server, Oracle, and SingleStore. Supports Laravel 5.5+.
withRecursiveExpression) replace application-layer recursion with optimized SQL, reducing query complexity and improving performance.withExpression()/withRecursiveExpression(). No framework changes required.QueriesExpressions) for recursive relationships. Minimal boilerplate.DB::table() and DB::query(), preserving existing patterns.WITH RECURSIVE in stored procedures) with withRecursiveExpression.withExpression in INSERT/UPDATE/DELETE statements for derived data (e.g., batch updates using CTEs).try-catch blocks for unsupported features (e.g., cycle detection on older MariaDB).try {
return DB::withRecursiveExpressionAndCycleDetection(...)->get();
} catch (\Exception $e) {
return DB::withRecursiveExpression(...)->get();
}
config('app.enable_cte_recursion')) to toggle CTE usage during migration.^1.0) to avoid breaking changes.public function test_recursive_category_tree() {
// Seed a 5-level category hierarchy.
$categories = Category::withRecursiveExpression('tree', $query)->get();
$this->assertCount(15, $categories); // 1 + 2 + 3 + 4 + 5
}
toSql() and dd() to inspect generated queries:
$query = DB::table('users')->withRecursiveExpression('tree', $recursiveQuery);
\Log::debug($query->toSql(), ['bindings' => $query->getBindings()]);
SET cte_max_recursion_depth in PostgreSQL).parent_id in recursive tables)./*+ MATERIALIZE */ in Oracle).$query->withRecursiveExpression('tree', $recursiveQuery)->paginate(100);
staudenmeir/laravel-adjacency-list).pg_stat_activity (PostgreSQL) or EXPLAIN ANALYZE.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Infinite recursion | Query timeout or server crash | Use cycle detection (MariaDB/PostgreSQL) or application-level safeguards. |
| Unsupported database feature | Query fails silently | Feature detection + fallback logic (e.g., non-materialized CTEs). |
| Large hierarchy depth | Slow queries or timeouts | Implement depth-based pagination or denormalize. |
| Database-specific syntax errors | Deployment failures | Test on all target databases pre-release. |
| Concurrent writes to hierarchical data | Inconsistent results | Use transactions for write operations. |
How can I help you explore Laravel packages today?