How to Print or Get Last Executed Query in Laravel

How to Print or Get Last Executed Query in Laravel

Laravel print or get last executed query; In this tutorial, you will learn how to enable query log for print or get last executed query in Laravel 10, 9, and 8 apps.

How to Print or Get Last Executed Query in Laravel

Use the following methods to enableQuery log for print or get last executed query in laravel 10, 9, 8 apps:

  • Solution 1 – Laravel Last Query using toSQL()
  • Solution 2 – Laravel Get Last Executed MySQL Query

Solution 1 – Laravel Last Query using toSQL()

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

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

Solution 2 – Laravel Get Last Executed MySQL Query

Before getting the last executed mysql query, you need to enableQuery log in Laravel app using query builder’s DB::enableQueryLog() method.

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.

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

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of 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 from a starting stage. As well as demo example.

Leave a Reply

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