0

I have made a JSON search engine for our APIs.

The logic for assembling queries is as follows;

Laravel macro is made to enable search method on Eloquent models which creates an instance of the class and runs the search method:

/**
 * @var $this Builder
 */
$searcher = new Searcher($this, $request);
$searcher->search();

To keep things separated, request parameter classes which have URL query logic are instantiated dynamically and have the same query builder as a dependency. Inside foreach loop the following is executed:

new $parameter($this->request, $this->builder, $this->modelConfig);

In order to see what was actually searched for, I have set the log to write the actual query and bindings

Log::info('[Search] SQL: ' . $this->builder->toSql() . " Bindings: " . implode(', ', $this->builder->getBindings()));

Now the issue I'm having is that when loading related models (using ->with() in one of the request parameters (RelationsParameter) that I do get what I asked for, so model is loaded together with relations passed to it, however that is never reflected in the query.

I will always end up with SELECT * FROM table WHERE something, without the mention of the related table. Is there a way to get the underlying query as well?

Norgul
  • 4,613
  • 13
  • 61
  • 144
  • Did you try this https://stackoverflow.com/questions/41140975/laravel-eloquent-display-query-log ? – Yz. Jul 10 '20 at 07:52

2 Answers2

0

You could wrap your code around Laravel's query logger:

\DB::connection()->enableQueryLog();
// your code
\DB::connection()->disableQueryLog();

After that, you may get the logged queries with \DB::getQueryLog().

However, if you just want to log while developing, I would use the barryvdh/laravel-debugbar package.

halloei
  • 1,892
  • 1
  • 25
  • 45
0

I have been digging deeper within Laravel itself, and the answer to the question as why doesn't the toSql() method dump the relation SQL as well is because it gets compiled before eagerLoadRelations method is triggered.

So currently, it is not possible to dump the whole SQL while operating with query builders.

What halloei suggests will dump all queries executed, however this does not help me at this point because it requires me to add the code outside my package.

Norgul
  • 4,613
  • 13
  • 61
  • 144