Laravel Eloquent: Auxiliary function for database debugging
When working with Laravel Eloquent, database queries can become very complex and errors creep in quickly. Finding them often turns out to be complicated. Especially if you copy a code in the heat of the moment, but have not fully adapted it, you have forgotten to change a variable name or you take over existing software projects without checking them. The actual database query can quickly help here.
Example:
The schedule table contains a grown construct, the user receives the primary key of the user table. In this case, a numeric ID:
Preparation:
To start, we need the HelperServiceProvider app (app/Providers/HelperServiceProvider.php). In this file the "Helpers" (helper functions) are registered. The HelperServiceProvider reads all files in the folder "app/Helpers" and includes them automatically.
The HelperServiceProvider must then be registered in the app. To do this, add the newly created HelperSeviceProvider to the config/app.php file in the "providers" section:
Functions:
As you can see in the third line, we use the builder from Eloquent for the help function: (https://laravel.com/docs/8.x/eloquent). Data that was entered by mistake will receive an error message. ddsql($query->get())
After completing the above file, you can use the "ddsql()" function in your code. Here is an example of the function in use (a block of code from the page https://laravel.com/docs/8.x/eloquent#advanced-subqueries was used for this):
This approach offers a good starting point for turning the performance screw.