title: Laravel query builder macro on loaded models
body: <p>I have developed a <a href="https://github.com/asseco-voice/laravel-json-search" rel="nofollow noreferrer">package to enable search method on Eloquent models with JSON</a>.</p>
  <p>The engine currently works in a way that a query is appended for supported parameters depending on values provided.</p>
  <pre><code>Builder::macro('search', function (Request $request) {
      /**
       * @var $this Builder
       */
      $searcher = new Searcher($this, $request);
      $searcher-&gt;search();
      return $this;
  });
  </code></pre>
  <p>Which in turn runs the following:</p>
  <pre><code>/**
   * Perform the search
   *
   * @throws Exceptions\SearchException
   */
  public function search(): void
  {
      $this-&gt;appendQueries();
      Log::info('[Search] SQL: ' . $this-&gt;builder-&gt;toSql());
  }
  
  /**
   * Append all queries from registered parameters
   *
   * @throws Exceptions\SearchException
   */
  protected function appendQueries(): void
  {
      foreach ($this-&gt;requestParametersConfig-&gt;registered as $parameter) {
          $requestParameter = $this-&gt;createRequestParameter($parameter);
          $requestParameter-&gt;appendQuery();
      }
  }
  
  protected function createRequestParameter($parameter): AbstractParameter
  {
      return new $parameter($this-&gt;request, $this-&gt;builder, $this-&gt;modelConfig);
  }
  </code></pre>
  <p>Request parameters are registered within configuration file and point to request parameter classes to have everything modular.</p>
  <p>Now this works great if used on a something like <code>index</code> endpoint or a custom <code>search</code> endpoint, but I would like to extend the functionality to <code>show</code> as well. The issue being here that with route model binding, the model is already loaded when I fetch it.</p>
  <p>Let's take relationships for example. I have a request parameter which when used loads relationships on a given model:</p>
  <pre><code>www.example.com/api/contacts?relations=(phones)
  </code></pre>
  <p>will load <code>phones</code> relations on <code>Contact</code> model by doing this:</p>
  <pre><code>/**
   * Append the query to Eloquent builder
   * @throws SearchException
   */
  public function appendQuery(): void
  {
      $arguments = $this-&gt;getArguments();
  
      $this-&gt;builder-&gt;with($arguments);
  }
  </code></pre>
  <p>But when I do a <code>-&gt;with</code> on already loaded model followed by <code>-&gt;get()</code>, I just get list of all models with loaded relation.</p>
  <p>Is there a way to &quot;tap into&quot; already loaded model with query builder, or is it at this point already done deal, and I should pick up the ID on <code>show</code> route instead of resolving it, and then assemble the query?</p>