7

I'm using Laravel Lumen to build an API.

I've come to a point where I need to find out what SQL query is being generated by Eloquent. I know how to do this in Laravel 4 and Laravel 5 but i've tried the same code in Lumen and the query is blank?

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

echo 'Query<pre>';
    print_r($last_query);
exit;

The above code, when run in Laravel works fine - in Lumen the query is blank?

ajtrichards
  • 29,723
  • 13
  • 94
  • 101

2 Answers2

9

To get the query log in Laravel Lumen working you need to enable it:

DB::connection()->enableQueryLog();

You can add that code in to your controller, middleware, etc then use:

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

dd($lastQuery)

To print your query.

You can also use the following with eloquent:

$myModel = Users::where('active', true);

dd($myModel->getSql(), $myModel->getBindings());

You must run the getSql() and getBindings() before you call ->first() or ->get(), etc

ajtrichards
  • 29,723
  • 13
  • 94
  • 101
  • I'm using Lumen 5.7, and the above code only logs the likes df DB::select etc. Not eloquent model retrieval etc - which I was hoping it would. – Nigel Atkinson Apr 29 '19 at 14:17
  • @NigelAtkinson Have you tried `dd($eloquentQuery->toSql(), $eloquentQuery->getBindings());` – ajtrichards Apr 29 '19 at 17:34
  • 1
    Thanks ajtrichards, those do work, however I figured out the problem. I had LadaCache which caches eloquent queries in redis not quite as disabled as I thought. – Nigel Atkinson Apr 29 '19 at 23:46
5

Just call this after the query to keep it quick and simple:

echo $query->toSql();
spenibus
  • 4,339
  • 11
  • 26
  • 35
Mahen Nakar
  • 376
  • 2
  • 15