spatie/laravel-sql-commenter
Adds sqlcommenter-style comments to Laravel database queries, embedding context like controller and action. Makes it easy to trace slow or problematic SQL back to the exact code path, and works with tools like PlanetScale Query Insights.
QueryBuilder::macro, Model::boot), avoiding core framework modifications. Compatible with existing query logging (e.g., Laravel Debugbar, Sentry) or monitoring tools (e.g., New Relic, Datadog).SqlCommenter::addComment() or middleware, enabling integration with CI/CD pipelines, feature flags, or performance profiling.QueryBuilder::macro to intercept queries, which may conflict with other packages modifying the same hooks (e.g., query loggers). Test for hook precedence.AppServiceProvider) is more predictable than query builder macros, which may execute out of order. Risk: Comments might miss edge cases (e.g., raw PDO queries bypassing Eloquent).DB::raw() or dynamic SQL strings may not auto-comment. Requires manual annotation or wrapper functions.composer require spatie/laravel-sql-commenter.AppServiceProvider:
use Spatie\SqlCommenter\SqlCommenter;
SqlCommenter::addComment('controller={controller},action={action}');
request_id or user_id via middleware:
SqlCommenter::addComment('request_id=' . request()->header('X-Request-ID'));
composer.json for LTS compatibility.DB::listen).SHOW VARIABLES LIKE 'sql_mode' for MySQL).SqlCommenter.config/sql-commenter.php).dd())./*controller=UsersController,action=store,user_id=123*/).| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Comments break SQL parsing | Query fails in some DBs | Test with target DB; use syntax validation. |
| Middleware conflicts | Comments missing for some queries | Use SqlCommenter::macro for deterministic hooks. |
| Over-commenting | Logs become unreadable | Restrict to staging/dev; use feature flags. |
| Raw SQL bypasses comments | Critical queries lack context | Wrap raw SQL in a macro (e.g., DB::commented()). |
controller=*").How can I help you explore Laravel packages today?