How to Get or Print Last Executed Query in Laravel

How to Get or Print Last Executed Query in Laravel

To get or print the last executed query in Laravel, simply enable the query log using the DB::enableQueryLog() method and print the last executed query using the DB::getQueryLog() method.

Also, you can use toSQL() function with a query, and print the last executed query.

How to Print or Get Last Executed Query in Laravel

Here are two ways how to enableQuery log for print or get last executed query in laravel 11, 10, and 9 apps:

Solution 1 – Get Last Query using toSQL()

To get current SQL query you can do it with Laravel query builder’s toSql() method; as follows:

        $query = User::select("*")->toSql();
            
        dd($query);

Solution 2 – Get Last Executed Query using enableQueryLog

The easiest way to get or print the last executed query is to simply enable the query log using the DB::enableQueryLog() method and print the last executed query using the DB::getQueryLog() method; You can use it like this:

      DB::enableQueryLog();
  
      $users = User::select("*")->get();
      $quries = DB::getQueryLog();
  
      dd($quries);

The enableQueryLog feature in Laravel allows developers to log and analyze the database queries executed during the execution of their application. It provides valuable insights into the queries being performed, helping with debugging, performance optimization, and understanding the interaction between the application and the database.

Note:- If you do not enable query log in Laravel and will print the last executed query then you will not get any result.

Conclusion

That’s it; You have learned how to use enableQueryLog() and getQueryLog() method to print or get the last executed query in laravel 11, 10, and 9 apps.

if you have any questions or queries then you can ask me by commenting in the comment box or you can mail us at [email protected].

Recommended Laravel Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *