Sometimes we face issues in getting data or getting the wrong data. We can resolve this type of issue using row SQL queries but for that, we need to convert the eloquent queries into row queries. Laravel provides two ways to get row queries.
- Using Laravel Eloquent methods
- Using the Laravel Query Log
Using Laravel Eloquent methods
This method to get the query of an Eloquent call is by using the toSql() method. This method returns the query without running it. but this method is not too useful with complex queries where a large set of relations or sub-queries are performing together.
The toSql() function will automatically convert model query into a row SQL query. Let's take an example to understand it.
Here, we write all code the same as normal query but instead of using get() method we will use toSql() method and it will convert the Eloquent query into a row SQL query.
Output :
Using the Laravel Query Log
In this method, we enable the Laravel framework to log every query executed between code blocks and get it using its method. The DB facade provides database methods one of them is enableQueryLog() which will tell the framework to start logging query.
Another method is used to get stored query logs which is getQueryLog(). Let's take an example for this method.
Output:
Here, before executing any query we have enabled query log and then executed multiple queries and at last we have printed all queries using die dump.
Conclusion
Here, both methods return row queries but in the first method, it will return only one query while we can use the second method to get all queries between code blocks. Another major difference between both methods is that first method get row query without executing while into second method executes a query and logs into the background.