How to get the raw SQL query from the Laravel Query Builder - TechvBlogs

How to get the raw SQL query from the Laravel Query Builder

Find out how to get the raw SQL query for a Laravel Eloquent call, or all of them if there are numerous.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

1 year ago

TechvBlogs - Google News

You might occasionally ask how to output the original SQL query from the Laravel query builder as a string. Thankfully, there are a few different ways to get this raw query in Laravel.

When troubleshooting problems with the Laravel query builder, you might wish to see the actual SQL query that is being executed for debugging purposes.

How to get the raw SQL query from the Laravel Query Builder

Here are some simple methods you can employ to immediately force the query Builder to publish its original SQL query as a string.

1. Using Laravel Eloquent methods

The query from an Eloquent call can first be obtained using the toSql() method. If you only want the query and don't want to update any data. This function is helpful because it returns the query without running it. However, this approach won't show the whole query if it's complicated or contains sub-queries.

User::query()
    ->where('created_at', '<', now()->subYear())
    ->toSql();

Output:

select * from `users` where `created_at` < ?

2. Using the Laravel Query Log

The second method uses the Laravel query log, which aggregates every query inside a request. Run your query, turn on this log, and dump the outcomes.

\DB::enableQueryLog();

User::query()
    ->where('created_at', '<', now()->subYear())
    ->toSql();

dd(\DB::getQueryLog());

You may see here particular information about the query that was run and how long it took to complete. It is straightforward to validate your data because data bindings are reported in the query logs if a query has them.

Thank you for reading this article.

Read Also: Importing large CSV files in MySQL using Laravel

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

Comments (0)

Comment


Note: All Input Fields are required.