How to Print Last Executed Query in Laravel?

Sovary March 25, 2023 489
1 minute read

Hello friend, if you have a big project to query database and want to know how does your query database is actually perform such in duration of manipulate as well as to whether your query statment is correct since Laravel using ORM which is manipulate data with PHP syntax. In this tutorial, we are going to learn how to get SQL statement in Laravel. Below example will help you handle in different way to print out SQL Query. 

We will use toSql() DB::enableQueryLog(), and DB::getQueryLog  in Laravel 9 to show SQL query which perform by this PHP syntax. So let's take a look at below examples.

Example #1 - Print as SQL Statement

<?php
  
namespace App\Http\Controllers;
use App\Models\User;
  
class UserController extends Controller
{
    public function index()
    {
        $sql= User::get()->toSql();
        dd($sql);
    }
}	

Output

select * from `users`

Example #2 - Get Last Query Statment Executed

<?php
  
namespace App\Http\Controllers;
   
use App\Models\User;
use DB;
    
class UserController extends Controller
{
    public function index()
    {
        // Enable log Query Statment;
        DB::enableQueryLog();
  
        $users = User::select("*")->get();
        $quries = DB::getQueryLog();
  
        dd($quries);
    }
}

Output

array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 28.23
  ]
]

This examples give you idea how to get log or debug as the result in SQL query in your Laravel application. Hope this would help your project. Have a nice day!

You might also like...

Laravel  PHP  Laravel 9  Query Builder 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him