Tags
Asked 2 years ago
17 Jun 2021
Views 143
Ed

Ed posted

How to Get the Query Executed in Laravel 5?

How to Get the Query Executed in Laravel 5?
andy

andy
answered Apr 27 '23 00:00

In Laravel 5, you can get the last executed query using the toSql() method on the query builder instance. Here's how to do it:

First, build your query using the Query Builder:



$users = DB::table('users')
            ->where('name', 'John')
            ->get();

This query selects all users with the name "John" from the users table.

Next, call the toSql() method on the query builder instance to get the raw SQL query:



$users = DB::table('users')
            ->where('name', 'John')
            ->get();

The $query variable now contains the raw SQL query that was executed for the query.

Alternatively, you can use the getQueryLog() method to get the list of all executed queries for the current request. Here's how to do it:

First, enable the Query log in Laravel by setting the DB_LOG_QUERIES environment variable to true in your .env file:



DB_LOG_QUERIES=true

Then, execute your query using the Query Builder:


$users = DB::table('users')
            ->where('name', 'John')
            ->get();

Finally, retrieve the list of executed queries using the getQueryLog() method:


$queries = DB::getQueryLog();
$lastQuery = end($queries);

The $lastQuery variable now contains an array representing the last executed query, including the SQL query itself and any query bindings.

Note that if you're using Eloquent models, you can also get the last executed query by calling the toSql() method on the query builder instance returned by the model. For example:



$user = User::where('name', 'John')->get();
$query = $user->toSql();

This will give you the raw SQL for the query that is being executed by the get() method on the User model.
Post Answer