Skip to content

Instantly share code, notes, and snippets.

@jaygaha
Created July 26, 2023 04:35
Show Gist options
  • Save jaygaha/672f70aea8dac99d2c3efd6643c5dc4c to your computer and use it in GitHub Desktop.
Save jaygaha/672f70aea8dac99d2c3efd6643c5dc4c to your computer and use it in GitHub Desktop.
Quickly Dumping Laravel Queries

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

Using Laravel Eloquent methods

To get the query from an Eloquent call without actually running it, you can use the toSql() method. This is useful when you only need to see the query and don't want to modify data. However, keep in mind that for complex queries or sub-queries, the toSql() method may not display the entire query.

Example:

$users = User::query()
	->where('is_active', 1)
    	->with(‘profile’)
    	->latest()
    	->limit(5)
    	->toSql();

Output:

select * from `users` where `is_active` = ? and `users`.`deleted_at` is null order by `created_at` desc limit 5

Using the Laravel Query Log

The second method in Laravel is the query log, which gathers all queries made during a request. To use it, enable the log, execute your query, and check the output.

Example:

use Illuminate\Support\Facades\DB;

DB::enableQueryLog();
$user = User::query()
            ->where('is_active', 1)
            ->with('profile')
            ->latest()
            ->limit(5)
            ->get();
dd(DB::getQueryLog());

Output:

array:2 [ // app/Models/User
  0 => array:3 [
    "query" => "select * from `users` where `is_active` = ? and `users`.`deleted_at` is null order by `created_at` desc limit 5"
    "bindings" => array:1 [
      0 => 1
    ]
    "time" => 5.6
  ]
  1 => array:3 [
    "query" => "select * from `profiles` where `profiles`.`membership_type` = ? and `profiles`.`user_id` =  ? and `profiles`.`deleted_at` is null"
    "bindings" => array:1 [
      0 => 0,
      1 => 1
    ]
    "time" => 1.38
  ]
]

This provides detailed info about the executed query and its execution time. If the query has data bindings, the log displays them, making it convenient to verify your data.

Using dd and dump

Use dd and dump methods when building a query to see current query bindings and SQL. dd stops the request and displays debug info, while dump shows debug info but allows the request to continue.

Example:

// using dd()
$user = User::query()
            ->where('is_active', 1)
            ->with('profile')
            ->latest()
            ->limit(5)
            ->dd();

// using dump()
$user = User::query()
            ->where('is_active', 1)
            ->with('profile')
            ->latest()
            ->limit(5)
            ->dump();

Output:

select * from `users` where `is_active` = ? and `users`.`deleted_at` is null order by `created_at` desc limit 5

array:1 [
  0 => 1
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment