How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array
By default, the query log is disabled in Laravel 5:
https://github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448
You will need to enable the query log by calling:
DB::enableQueryLog();
// and then you can get query log
dd(DB::getQueryLog());
or register an event listener:
DB::listen(
function ($sql, $bindings, $time) {
// $sql - select * from `ncv_users` where `ncv_users`.`id` = ? limit 1
// $bindings - [5]
// $time(in milliseconds) - 0.38
}
);
Some Tips
1. Multiple DB connections
If you have more than one DB connection you must specify which connection to log
To enables query log for my_connection
:
DB::connection('my_connection')->enableQueryLog();
To get query log for my_connection
:
print_r(
DB::connection('my_connection')->getQueryLog()
);
2. Where to enable query log ?
For an HTTP request lifecycle, you can enable query log in the `handle` method of some `BeforeAnyDbQueryMiddleware` [middleware][1] and then retrieve the executed queries in the [`terminate`][2] method of the same middleware.
class BeforeAnyDbQueryMiddleware
{
public function handle($request, Closure $next)
{
DB::enableQueryLog();
return $next($request);
}
public function terminate($request, $response)
{
// Store or dump the log data...
dd(
DB::getQueryLog()
);
}
}
A middleware's chain will not run for artisan commands, so for CLI execution you can enable query log in the artisan.start
event listener.
For example you can put it in the bootstrap/app.php
file
$app['events']->listen('artisan.start', function(){
\DB::enableQueryLog();
});
3. Memory
Laravel keeps all queries in memory. So in some cases, such as when inserting a large number of rows, or having a long running job with a lot of queries, this can cause the application to use excess memory.
In most cases you will need the query log only for debugging, and if that is the case I would recommend you enable it only for development.
if (App::environment('local')) {
// The environment is local
DB::enableQueryLog();
}
References
- https://laravel.com/docs/5.0/database#query-logging
Laravel 4, PHPUnit and DB::getQueryLog() always empty
This answer helped me:
[here]How to get the query executed in Laravel 5 ? DB::getQueryLog returning empty array
The Some Tips 1 Multiple DB connections
If you have more than one DB connection you must specify which connection to log
To enables query log for my_connection:
DB::connection('my_connection')->enableQueryLog();
To get query log for my_connection:
print_r(
DB::connection('my_connection')->getQueryLog()
);
Both enbleQueryLog()
and getQueryLog()
needed to specify the connection name
How do I get the query builder to output its raw SQL query as a string?
To output to the screen the last queries ran you can use this:
\DB::enableQueryLog(); // Enable query log
// Your Eloquent query executed by using get()
dd(\DB::getQueryLog()); // Show results of log
I believe the most recent queries will be at the bottom of the array.
You will have something like that:
array(1) {
[0]=>
array(3) {
["query"]=>
string(21) "select * from "users""
["bindings"]=>
array(0) {
}
["time"]=>
string(4) "0.92"
}
}
(Thanks to Joshua's comment below.)
Laravel collection fetch empty array but sql gives proper results
Try this:
$transectionDetails = Wallet_transaction::query();
$transectionDetails = $transectionDetails->select('kitchen_name','parent_id',DB::raw("CONCAT(f_name, ' ', l_name) AS name"),'transaction_amount','transaction_time','transaction_id')
->join('parent_details','wallet_transactions.parent_id', '=','parent_details.id')
->join('kitchens','parent_details.kitchen_id', '=','kitchens.id')
->whereNotNull('wallet_transactions.transaction_id')
->where('wallet_transactions.transaction_for',2);
if(!empty($post_data) && $post_data['parent_name'] != '') {
$transectionDetails = $transectionDetails->where(DB::raw("CONCAT(f_name, ' ', l_name)"), 'like', "'%".$post_data['parent_name'] ."%'");
$results = $transectionDetails->get();
dd($results);
}
You need to keep your query variable updated with the modifications you are applying to it.
I hope it helps
Laravel Eloquent display query log
First you have to enable query log
it can be done using
DB::connection()->enableQueryLog();
then you can use below code to see the query log
$queries = DB::getQueryLog();
if you want to see the last executed query
$last_query = end($queries);
to know more about logging see this https://laravel.com/docs/5.0/database#query-logging
Example
public function show(Order $order){
\DB::connection()->enableQueryLog();
$data = $order->all();
$queries = \DB::getQueryLog();
return dd($queries);
}
Get executed sql queries in Laravel
The problem is there's a difference in time of execution between the code executed inside the ::listen()
method and the lines before and after.
The code inside will be executed when a query is sent, while the other code is performed on startup of your app. Thus, after binding the function to the Database facade, no query is executed yet and $logs
will be empty.
For logging
You could try and let the DB listener write the queries to a file or have a look at this post: https://stackoverflow.com/a/27753889/2142071
For adding to request
Inside the listen
method use request()->request->add(['sql', $query->sql]);
to have the sql
variable available in the request object.
Laravel Query builder returns empty array despite it being not null
Because the where()
method thinks you're passing down a string to compare with the column value (and it fails because it's comparting the rgt
column value with the string "lft +1", literal).
If you want to use an expression, wrap it with raw()
:
->where('rgt', '=', \DB::raw('lft + 1'))
or use the whereRaw()
method directly:
->whereRaw('rgt = lft + 1')
Singular query scope returning empty array when nothing found
You're using a local scope as a relationship with the with()
method. You can't do that. You should use a local scope like this:
Model::someScope()->get();
Loading a single latest record for hasMany()
relation is pretty tricky. You need to create another relation and it must be hasOne()
.
Related Topics
How to Run a PHP File in a Scheduled Task (Windows Task Scheduler)
MySQLi Query Returns Only One Row
Create Programmatically a Woocommerce Product Variation With New Attribute Values
Run a PHP File in a Cron Job Using Cpanel
Does PHP Time() Return a Gmt/Utc Timestamp
How to Make a Simple Crawler in PHP
Connect PHP to Mssql Via Pdo Odbc
How to Test If a MySQL Query Was Successful in Modifying Database Table Data
Difference Between "Not Equal" Operators ≪≫ and != in PHP
Remove Script Tag from HTML Content
How to Iterate Over the Results in a MySQLi Result Set
Laravel View Not Found Exception
Accurate Way to Measure Execution Times of PHP Scripts
Accessing Outside Variable Using Anonymous Function as Params