Add Comments to Correlate User Code with SQL Queries in Laravel

Packages

July 5th, 2022

Add Comments to Correlate User Code with SQL Queries in Laravel

Laravel SQL Commenter is a package by Spatie to add comments to SQL queries made by Laravel. It uses sqlcommenter to augment SQL statements about the code:

1/* typical query */
2select * from users
3 
4/* comments added by this package */
5select * from "users"/*controller='UsersController',action='index'*/;

Once this package is installed, SQL comments get automatically included, and you can control what things are added to the comments and disable comments dynamically.

1use Spatie\SqlCommenter\SqlCommenter;
2 
3SqlCommenter::addComment('foo', 'bar');
4 
5// select * from "users"/*foo='bar'*/;

This package has the concept of a "commenter" class, which add useful information to queries, such as the controller and route information. Out of the box, this package includes the following commenters:

  • ControllerCommenter
  • RouteCommenter,
  • JobCommenter
  • FileCommenter
  • CurrentUserCommenter

You can also add custom commenter classes using the provided Commenter interface from this package.

You can learn about this package, get full installation instructions, and view the source code on GitHub. The author, Freek Van der Herten, wrote a post titled Add comments to SQL queries made by Laravel if you'd like to dive deeper into the background of this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.