title: Including relationships in Laravel API resource response
body: <p>My aim is to create a book store API endpoint with a ratings relationship. The relationship between the Book &amp; Rating is like this:</p>
  
  <p>Book model</p>
  
  <pre><code>/**
  * a book has many ratings
  */
  public function ratings()
  {
      return $this-&gt;hasMany(Rating::class, 'book_id')-&gt;orderBy('created_at', 'ASC');
  }
  </code></pre>
  
  <p>Rating model</p>
  
  <pre><code>/**
  * a rating belongs to a book
  */
  public function book()
  {
      return $this-&gt;belongsTo(Book::class);
  }
  </code></pre>
  
  <p>My BookResource looks like this</p>
  
  <pre><code>&lt;?php
  
  namespace App\Http\Resources;
  
  use Illuminate\Http\Resources\Json\JsonResource;
  
  use App\Http\Resources\RatingResource;
  
  class BookResource extends JsonResource
  {
      /**
       * Transform the resource into an array.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return array
       */
      public function toArray($request)
      {
          // return parent::toArray($request);
          return [
              'id'        =&gt; $this-&gt;id,
              'title'     =&gt; $this-&gt;title,
              'author'    =&gt; $this-&gt;author,
              'rating'    =&gt; RatingResource::collection($this-&gt;whenLoaded('ratings'))
          ];
      }
  }
  </code></pre>
  
  <p>My RatingResource looks like this:</p>
  
  <pre><code>&lt;?php
  
  namespace App\Http\Resources;
  
  use Illuminate\Http\Resources\Json\JsonResource;
  
  class RatingResource extends JsonResource
  {
      /**
       * Transform the resource into an array.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return array
       */
      public function toArray($request)
      {
          return parent::toArray($request);
      }
  }
  </code></pre>
  
  <p>I want to get all books along with the individual ratings and get a single book together with it's rating as well using both routes below in the api.php file:</p>
  
  <pre><code>Route::get('/books', function() {
      return BookResource::collection(Book::all());
  });
  
  Route::get('books/{book}', function(Book $book) {
      return new BookResource($book);
  });
  </code></pre>
  
  <p>When I make a get request to <code>http://12.0.0.1:8000/api/books</code> on postman, I get all the books but the ratings are not loaded. The same thing happens when I make a get request to <code>http://12.0.0.1:8000/api/books/1</code>, the book is returned without the rating.</p>
  
  <p>How are relationships loaded based on v5.7 <a href="https://laravel.com/docs/5.7/eloquent-resources#data-wrapping" rel="nofollow noreferrer">doc</a></p>