Reputation: 276
Please, how can I do to get the response time when executing eloquent query ? for example:
$arf = App\Roles::where('description','test')->get()
Thanks
Upvotes: 2
Views: 4130
Reputation: 11034
Laravel itself define a microtime
in index.php
define('LARAVEL_START', microtime(true));
So you should do the same after the query and calculate the difference
$begin = microtime(true);
$arf = App\Roles::where('description','test')->get();
$end = microtime(true) - $begin;
Now $end
is the response time
Comparing against the globally defined microtime may not be accurate as HTTP requests go through a pipeline to reach the query
You can also listen to query events and access the time
From the docs
\DB::listen(function ($query) {
info('Query took ' . $query->time);
});
And that is coming from Illuminate\Database\Events\QueryExecuted
here
<?php
namespace Illuminate\Database\Events;
class QueryExecuted
{
/**
* The SQL query that was executed.
*
* @var string
*/
public $sql;
/**
* The array of query bindings.
*
* @var array
*/
public $bindings;
/**
* The number of milliseconds it took to execute the query.
*
* @var float
*/
public $time;
/**
* The database connection instance.
*
* @var \Illuminate\Database\Connection
*/
public $connection;
/**
* The database connection name.
*
* @var string
*/
public $connectionName;
/**
* Create a new event instance.
*
* @param string $sql
* @param array $bindings
* @param float|null $time
* @param \Illuminate\Database\Connection $connection
* @return void
*/
public function __construct($sql, $bindings, $time, $connection)
{
$this->sql = $sql;
$this->time = $time;
$this->bindings = $bindings;
$this->connection = $connection;
$this->connectionName = $connection->getName();
}
}
Upvotes: 3
Reputation: 953
Query Execution
\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
$sql = $query->sql;
$time = $query->time;
$connection = $query->connection->getName();
Log::debug('query : '.$sql);
Log::debug('time '.$time);
Log::debug('connection '.$connection);
});
Query
StaffRegister::all();
Output
[2021-03-14 08:00:57] local.DEBUG: query : select * from `staff_registers`
[2021-03-14 08:00:57] local.DEBUG: time 0.93
[2021-03-14 08:00:57] local.DEBUG: connection mysql
complete structure
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Log;
use App\Models\StaffRegister;
class AuthController extends Controller
{
public function index(){
\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
$sql = $query->sql;
$time = $query->time;
$connection = $query->connection->getName();
Log::debug('query : '.$sql);
Log::debug('time '.$time);
Log::debug('connection '.$connection);
});
$obj = StaffRegister::all();
return $obj;
}
}
Upvotes: 0
Reputation: 50481
You could potentially use the query log.
DB::enableQueryLog();
// ... query
dump(DB::getQueryLog());
The log should include the times for the queries.
Upvotes: 4