title: Adding filter to eloquent resource to attach relationship conditionally
body: <p>Laravel 5.8
  PHP 7.4</p>
  
  <p>I want to load the relationships conditionally like</p>
  
  <pre><code>http://127.0.0.1:8000/api/posts 
  </code></pre>
  
  <p>and </p>
  
  <pre><code>http://127.0.0.1:8000/api/posts/1 are my end points now, I want to load comments like
  </code></pre>
  
  <p><code>http://127.0.0.1:8000/api/posts/?include=comments</code> and </p>
  
  <pre><code>http://127.0.0.1:8000/api/posts/1/?include=comments
  </code></pre>
  
  <p>If the query parameter is there, only then it should load comments with posts or it should load only posts/post</p>
  
  <p>I am doing this by referring a <a href="https://medium.com/@matthew.erskine/laravel-5-5-eloquent-resources-get-query-param-filters-9101edad2d95" rel="nofollow noreferrer">blog post</a> </p>
  
  <p>now, <strong>RequestQueryFilter</strong></p>
  
  <pre><code>&lt;?php
  namespace App\Http\Resources;
  use Illuminate\Http\Request;
  class RequestQueryFilter
  {
      public function attach($resource, Request $request = null)
      {
          $request = $request ?? request();
          return tap($resource, function($resource) use($request) {
              $this-&gt;getRequestIncludes($request)-&gt;each(function($include) use($resource) {
                  $resource-&gt;load($include);
              });
          });
      }
      protected function getRequestIncludes(Request $request)
      {
          // return collect(data_get($request-&gt;input(), 'include', [])); //single relationship
          return collect(array_map('trim', explode(',', data_get($request-&gt;input(), 'include', [])))); //multiple relationships
      }
  }
  </code></pre>
  
  <p>and in helper</p>
  
  <pre><code>&lt;?php
  if ( ! function_exists('filter') ) {
      function filter($attach) 
      {
          return app('filter')-&gt;attach($attach);
      }
  }
  ?&gt;
  </code></pre>
  
  <p>in PostController</p>
  
  <pre><code>public funciton show(Request $request, Post $post) {
      return new PostResource(filter($post));
  }
  </code></pre>
  
  <p>but when I am trying to retrieve </p>
  
  <pre><code>http://127.0.0.1:8000/api/posts/1/?include=comments getting no comments, with no error in log
  </code></pre>
  
  <p>A work around will be PostResource</p>
  
  <pre><code> public function toArray($request)
      {
          // return parent::toArray($request);
          $data = [
              'id' =&gt; $this-&gt;id,
              'name' =&gt; $this-&gt;title,
              'body' =&gt; $this-&gt;content,
          ];
  
          $filter = $request-&gt;query-&gt;get('include', '');
  
          if($filter){
            $data[$filter] = $this-&gt;resource-&gt;$filter;
          }
  
          return $data;
      }
  </code></pre>